High performance, high resilient JSP and servlet optimization

Source: Internet
Author: User
Tags garbage collection http request serialization sessions zip

Is your Java application running very slowly? Can they afford to keep up with the rising traffic? This article describes the development of high-performance, highly resilient JSP pages and the performance optimization of the servlet technology. The idea is to build as fast as possible and adapt to a growing number of users and their requests. In this article, I'm going to take you through the performance tuning techniques that have been practiced and proven, which will greatly improve the performance of your servlet and JSP pages, and hence the performance of Java EE. Parts of these technologies are used in the development phase, such as the design and coding phases. Another part of the technology is related to configuration.

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

The servlet's init () method is invoked by the server after the servlet instance is created and before any requests are processed by the servlet. This method is invoked only once in the life cycle of the servlet. To improve performance, cache static data in init () or complete costly operations to complete during initialization. For example, a best practice is to use a JDBC connection pool that implements the Javax.sql.DataSource interface. DataSource is obtained from the Jndi tree. Using Jndi to find DataSource every time you invoke SQL is a very expensive task and severely affects the performance of your application. The init () method of the servlet can be used to get 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 loading of servlet and JSP

After each modification of servlet/jsp, you will have to reboot the server. This feature is considered useful in the development phase because of the reduced development time by the automatic loading feature. However, it is very expensive at run time; servlet/jsp due to unnecessary loading, it increases the burden of class loaders and results in poor performance. Again, this will make your application strange conflicts occur because classes that have been loaded by a type loader cannot collaborate with classes that are loaded by the current class loader. Therefore, in order to get better performance in the running environment, turn off the servlet/jsp automatic loading function.

Technology 3: Control HttpSession

Many applications require a range of client requests, so they can be associated with each other. Because the HTTP protocol is stateless, web-based applications need to be responsible for maintaining such a state called session. To support applications that must maintain state, the Java servlet technology provides an API for managing sessions and allowing multiple mechanisms to implement sessions. The HttpSession object acts as a session, but it costs money to use it. Whenever HttpSession is used and rewritten, it is read by the servlet. You can improve performance by using the following techniques:

Do not create a default httpsession in a JSP page: By default, JSP pages create httpsession. If you are not httpsession in a JSP page, to save performance overhead, use the following page instructions to avoid automatically creating HttpSession objects:

 < %@ 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 at a time. This will force Java serialization and increase the computational overhead. Due to the cost of serialization, the throughput of the system decreases as the data objects in the HttpSession object are increased.

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

Set timeout value: A servlet engine has a default timeout value. If you do not delete the session or use the session until it times out, the servlet engine will remove the session from memory. Because of the overhead on memory and garbage collection, the greater the timeout value of the session, the greater the impact on system elasticity and performance. Try setting the timeout value for the session as low as possible.

Technology 4: Using gzip compression

Compression is the practice of removing redundant information and describing your information in as small a space as possible. Using gzip (GNU Zip) compression documents can effectively reduce the time to download HTML files. The smaller the amount of information you have, the faster they are sent out. Therefore, if you compress the content generated by your Web application, it will reach the user and appear on the user's screen faster. Gzip compression is not supported by any browser, but it is easy to check whether a browser supports it and sends gzip compressed content to the browser. The following code snippet shows how to send the 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 includes gzip, choose gzip.
If the header includes 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 guarantees that the servlet processes only one request at a time. If a servlet implements this interface, the servlet engine creates a separate servlet instance for each new request, which causes a lot of overhead. If you need to troubleshoot thread-safety issues, use a different approach instead of this interface. Singlethreadmodel is no longer advocated for use in Servlet 2.4.

Technology 6: Using the thread pool

The servlet engine creates a separate thread for each request, assigns the thread to the service () method, and then deletes the thread after the service () method has finished executing. By default, the servlet engine may create a new thread for each request. Because the overhead of creating and deleting threads is expensive, this default behavior lowers the performance of the system. We can use the thread pool to improve performance. Configure a thread pool, based on the expected number of concurrent users, to set the minimum and maximum number of threads Cheng Chili, and the minimum and maximum value for growth. At first, the servlet engine created a thread pool with a number of threads equal to the minimum number of threads in the configuration. The servlet engine then assigns a thread in the pool to a request instead of creating a new thread each time, and after the operation is complete, the servlet engine puts the thread back into the thread pool. With thread pooling, performance can be significantly improved. If you want, you can create more threads based on the maximum number of threads and the number of increases.

Technology 7: Choosing the right inclusion mechanism

In a JSP page, there are two ways to include a file: including directives (<%@ include file= "test.jsp"%>) and including actions (< Jsp:include page= "test.jsp" flush= "true"/ >). Include instructions to include the contents of a specified file in the compilation phase, for example, when a page is compiled into a servlet. Include actions that include the contents of a file during the request phase, for example, when a user requests a page. Include instructions faster than including actions. Therefore, the use of include directives will result in better performance unless the included files are frequently changed.

Technique 8: Use the appropriate range in the Usebean action

One of the most powerful ways to use JSP pages is to work with JavaBean components. JavaBean Use < jsp:usebean> tags can be embedded in the JSP page. The syntax is as follows:

< Jsp:usebean id= "name" scope= "Page|request|session|application" class=
"Package.classname" type= "TypeName" >
</jsp:usebean>

The scope property describes the visible range of the bean. The default value for the Scope property is page. You should choose the right range based on your application requirements, otherwise it will affect the performance of the application.

For example, if you need an object that is dedicated to some request, but you set the scope to session, that object will remain in memory after the request has ended. It will remain in memory unless you explicitly remove it from memory, invalidate the session, or timeout the session. If you do not select the correct range attribute, the cost of memory and garbage collection will affect performance. So set the appropriate range for the objects and delete them immediately after you run out of them.

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.