High-performance, high-flexibility JSP and Servlet Performance Optimization

Source: Internet
Author: User
Tags ranges

Is your J2EE application running slowly? Can they withstand rising traffic volumes? This article describes how to develop high-performance and highly elastic JSP pages and Servlet performance optimization technologies. It means to build as fast as possible and adapt to the increasing number of users and their requests. In this article, I will lead you to learn the proven performance Adjustment Technology, which will greatly improve the performance of your servlet and jsp pages, and thus improve the performance of J2EE. These technologies are used in the development phase, such as the design and coding phase. Other technologies are related to configuration.

Technology 1: cache data in the HttpServlet init () method

The server will call the servlet init () method after creating the servlet instance and before the servlet processes any request. This method is called only once in the servlet lifecycle. To improve performance, cache static data in init () or complete expensive operations to be completed during initialization. For example, a best practice is to use the JDBC connection pool that implements the javax. SQL. DataSource interface. DataSource is obtained from the JNDI tree. Every time an SQL statement is called, it is very expensive to use JNDI to search for DataSource, which seriously affects the application performance. Servlet's init () method can be used to obtain DataSource and cache it for later reuse:

public class ControllerServlet extends HttpServlet
  {
    private javax.sql.DataSource testDS = null;

    public void init(ServletConfig config) throws ServletException
    {
     super.init(config);
     Context ctx = null;
     try
     {
       ctx = new InitialContext();
       testDS = (javax.sql.DataSource)ctx.lookup("jdbc/testDS");
     }
     catch(NamingException ne)
     {
       ne.printStackTrace();
      }
      catch(Exception e)
      {
       e.printStackTrace();
      }
    }

    public javax.sql.DataSource getTestDS()
     {
       return testDS;
     }
    ...
    ...
  }

Technology 2: Disable Automatic servlet and Jsp Loading

After modifying Servlet/JSP, You have to restart the server. Because the automatic loading function reduces development time, this function is considered very useful in the development stage. However, it is very expensive in the running stage; servlet/JSP causes poor performance due to unnecessary loading and increasing the load on the class loader. Similarly, this will cause a strange conflict between the classes loaded by a certain type of loader and the classes loaded by the current class loader. Therefore, in the runtime environment, disable the automatic loading function of servlet/JSP for better performance.

Technology 3: Control HttpSession

Many applications need a series of client requests, so they can be associated with each other. Because the HTTP protocol is stateless, Web-based applications need to maintain such a session state. To support applications that require State maintenance, Java servlet technology provides APIs for managing sessions and allowing multiple mechanisms to implement sessions. The HttpSession object plays the role of the session, but the cost is required to use it. Whenever an HttpSession is used and overwritten, it is read by the servlet. You can use the following technologies to improve performance:

Do not create the default HttpSession on the JSP page: by default, the JSP page creates an HttpSession. If you do not need HttpSession on the JSP page, to save performance overhead, use the following page command to avoid automatically creating an HttpSession object:

 < %@ page session="false"%>

Do not store large object graphs in HttpSession: If you store data as a large object graph in HttpSession, the application server will have to process the entire HttpSession object each time. This will force Java serialization and increase computing overhead. Due to the serialization overhead, as the data objects stored in the HttpSession object increase, the system throughput will decrease.

Release HttpSession after use: When HttpSession is not used, use HttpSession. invalidate () to invalidate the sesion.

Set the timeout value: a servlet engine has a default timeout value. If you do not delete a session or keep using it for a long time, the servlet engine will delete the session from the memory. Due to the overhead of memory and garbage collection, the larger the session Timeout value, the greater the impact on system elasticity and performance. Try to set the session Timeout value as low as possible.

Technology 4: gzip Compression

Compression is used to delete redundant information and describe your information with as little space as possible. Using gzip (GNU zip) to compress a document can effectively reduce the time needed to download HTML files. The less information you have, the faster they are delivered. Therefore, if you compress the content produced by your web application, the faster it reaches the user and is displayed on the user screen. Not all browsers support gzip compression, but it is easy to check whether a browser supports it and send gzip compressed content to the browser. The following code snippet illustrates how to send compressed content.

Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws IOException, ServletException
{

OutputStream out = null

// Check the Accepting-Encoding header from the HTTP request.
// If the header contains des gzip, choose GZIP.
// If the header already des compress, choose ZIP.
// Otherwise choose no compression.

String encoding = request. getHeader ("Accept-Encoding ");

If (encoding! = Null & encoding. indexOf ("gzip ")! =-1)
{
Response. setHeader ("Content-Encoding", "gzip ");
Out = new GZIPOutputStream (response. getOutputStream ());
}
Else if (encoding! = Null & encoding. indexOf ("compress ")! =-1)
{
Response. setHeader ("Content-Encoding", "compress ");
Out = new ZIPOutputStream (response. getOutputStream ());
}
Else
{
Out = response. getOutputStream ();

}
...
...
}

Technology 5: Do not use SingleThreadModel

SingleThreadModel ensures that the servlet processes only one request at a time. If a servlet implements this interface, the servlet engine will create a separate servlet instance for each new request, which will cause a large amount of system overhead. If you need to solve the thread security problem, use other methods to replace this interface. SingleThreadModel is no longer recommended in Servlet 2.4.

Technology 6: Use a thread pool

The servlet engine creates a separate thread for each request, assigns the thread to the service () method, and deletes the thread after the service () method is executed. By default, the servlet engine may create a new thread for each request. Because the overhead of creating and deleting threads is very expensive, this default behavior reduces the system performance. We can use the thread pool to improve performance. Configure a thread pool based on the expected number of concurrent users and set the minimum and maximum number of threads in the thread pool and the minimum and maximum value of growth. At first, the servlet engine created a thread pool with the same number of threads as the minimum number of threads in the configuration. Then, the servlet engine assigns a thread in the pool to a request instead of creating a new thread each time. After the operation is completed, the servlet engine places the thread back to the thread pool. With the thread pool, the performance can be significantly improved. If necessary, you can create more threads based on the maximum number of threads and the number of threads that increase.

Technology 7: select the proper inclusion mechanism

On the JSP page, two methods can be used: including commands (<% @ include file = "test. jsp "%>) and include actions (<jsp: include page =" test. jsp "flush =" true "/> ). Including Commands include the content of a specified file in the compilation phase; for example, when a page is compiled into a servlet. An action includes the file content in the request phase. For example, when a user requests a page. Including commands is faster than including actions. Therefore, unless the included files change frequently, using the include command will provide better performance.

Technology 8: Use appropriate ranges in useBean actions

One of the most powerful ways to use JSP pages is to work with the JavaBean Component. JavaBean can embed the <jsp: useBean> label into the JSP page. Syntax:

<Jsp: useBean id = "name" scope = "page | request | session | application" class =
"Package. className" type = "typeName">
</Jsp: useBean>

The scope attribute specifies the visible range of bean. The default value of the scope attribute is page. You should select the correct range based on your application needs, otherwise it will affect the application performance.

For example, if you need an object dedicated to some requests, but you set the range to session, the object will be retained in the memory after the request ends. It will remain in the memory unless you explicitly delete it from the memory, make the session invalid, or the session times out. If you do not select the correct range attribute, performance will be affected due to memory and garbage collection overhead. Therefore, you can set appropriate ranges for objects and delete them immediately after they are used up.

Related Article

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.