Servlet and JSP Performance tuning technology

Source: Internet
Author: User
Tags object character set error handling garbage collection header http request sql thread
Js|servlet| Performance Overview

In this article, Rahul Chaudhary describes the use of the Performance tuning technology (PTT performance-tuning techniques) to enhance the performance of servlets and JSP to improve the performance of your Java EE application. The author assumes that the reader has basic servlets and jsps knowledge.

Is your Java application running slowly? Can they meet enough pressure? This article will describe how to use the Performance tuning technology (PTT performance-tuning techniques) in developing high-performance applications and JSPs and Servlets. Using these technologies, you can build faster, more robust systems to meet the needs of more users or more requests. In this article, I'm going to take you through the actual practice of testing how to adjust performance to improve the slow performance of your servlets and JSP pages, and ultimately to improve the performance of your Java EE application. Some of these technologies are used during the development process, that is, when you are designing a system or writing code. Others are related to the configuration of the technology.

Adjustment Method 1: Caching Data using the HttpServlet init () method

The application server invokes the Init () method of the servlet before any requests are processed when the servlet begins to construct. Called only once in the life cycle of the servlet. The Init () method is used to improve performance during initialization by caching static data or by completing a resource-intensive operation.

For example, using the JDBC Connection pool is one of the best practices when invoking the Javax.sql.DataSource interface. Relies on the Jndi (Java Naming and service interface) tree to obtain datasource. If you do a jndi lookup datasource every SQL call, you will have a serious impact on the application service. The init () method of the servlet will be used to obtain the DataSource and cache it for later use.

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;

}

......

......

}

Adjustment Method 2: Disable automatic overloading of servlet and JSP

In order to save development time, servlet/jsp containers in the development phase provide automatic overload function, so that you do not need to restart the service after modifying the servlet/jsp. However, under the production environment, it is expensive, because there is no need to reload the operation, so it brings a very good performance impact. At the same time, some kinds of strange conflicts may also occur when some classes are loaded and some are loaded. Therefore, in the Java EE production environment to turn off the automatic loading function can get better performance.

One, in a large number of Java EE Project under a lot of pressure testing, in the development mode inexplicably error, part of the request task failed, because of the loading class caused by the system conflict.

Second, in another large-scale Java-EE project practical application process, a large number of users to allow enough to meet the user's system in the edge of paralysis, after the system, database, application server, etc. after adjustment, eventually did not solve the problem. Finally have to exclude personnel to solve the scene, and finally found the problem is this reason. The incident only occurred the day before yesterday.

Adjustment Method 3: Control HttpSession

Many application services require a range of customer requests, and these requests are interdependent. Because the HTTP protocol is stateless, web-based application systems must use session technology to maintain connectivity. To implement state management for application services, the Java servlet technology provides a set of APIs for session management by using HttpSession objects, but while using this feature, the HttpSession object reads and writes regardless of any request made by the servlet. The server also assumes the system overhead of the response. You can use the following methods to improve performance.

By default, do not create the Httpsessions object in the JSP page, the JSP page will automatically create httpsessions by default, if you do not need httpsessions in your JSP page, in order to save some performance, Use the following page directives to avoid automatically creating Httpsessions objects.

<;%@ page session= "false"%>

Do not store large objects to HttpSession: If you store large object data into HttpSession, the application server has to handle the entire httpsession in every request, which will force the serialization of Java to consume a large amount of system resources. The performance of the application service will be reduced due to the serialization of Java operations.

Release Httpsessions objects at the end: Use the Httpsession.invalidate () method to eliminate sessions when they are not needed.

Set timeout value for session: The servlet has a default timeout value. If you are in this time, you have neither removed it nor used it (for any service requests), the Servlet service will automatically destroy it. Because of the recovery of memory and garbage, the larger the timeout value, the greater the performance impact on the server. So, keep the session timeout to a minimum as much as possible.

Adjustment Method 4: Using gzip compression

Compression is an operation that places a surplus of information so that you can use the smallest amount of space to store it. Using gzip (GNU Zip) compression content can significantly reduce the time to download HTML files. The smaller the information content, the faster the transmission. Therefore, if you compress content when you build a Web application, you can transfer it faster and display it on the user's screen. Since not every browser supports gzip compression, you must simply check to see if the browser supports it.

The following code shows an example of how to send a 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 ();

}

......

......

}

Adjustment Method 5: Do not use Singlethreadmodel

The Singlethreadmodel interface ensures that the servlet accepts only one request at a time. If the servlet implements this interface, the servlet will create an isolated Servelet instance for each new request, which can cause significant overhead. If you need to handle thread-safety issues, you can replace this approach with other methods. The Singlethreadmodel interface is already opposed to use in servlet2.4.

Adjustment Method 6: Using the thread pool

The servlet engine creates an isolated thread for each request, assigns the thread to the service () method, and removes the thread after it has finished executing. By default, the Servlet engine creates a new thread for each request. Because creating and eliminating threads requires system overhead, this behavior can cause performance problems. You can improve performance by using line pool. Configure the maximum, minimum, and increased number of thread pools, depending on the number of concurrent users you expect. When the service is started, the servlet engine creates a thread pool with the smallest number of threads. The servlet engine then assigns a thread to each request, replaces the original creation of the new thread, and returns the thread to the thread pool after processing completes. With a thread pool, performance can be significantly improved. If necessary, more threads are created and added to the pool for more requests, depending on the maximum and increased number of threads.

Adjustment Method 7: Select the correct inclusion mechanism

There are two ways to use include files in JSP: Include directives (<;%@ include file= "test.jsp"%>) and include actions (<;jsp:include page= "test.jsp" flush= "true"/ >). The containing instruction contains the contents of the file during conversion, that is, when a page is converted into a servlet. The containing action contains the contents of the file during the request processing phase, that is, when a user requests a page. Contains instructions faster than include actions. Therefore, unless the content that is included changes frequently, you should use the include directive to promote performance.

Adjustment Method 8: Select the correct range to use the Usebean action

A powerful feature of JSP pages is the interactive use of JavaBeans components in the JSP. By using the <;jsp:useBean> action tag, JavaBeans can be directly 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 specifies the scope of the bean. Its default value is page. You can choose the right range according to your system requirements. Otherwise, it will affect the performance of the application system.

For example, if you need an object to be used only as a request, but your scope is set to session, the object will remain in memory after you complete the request. Until you know it clearly, by destroying the session, or the session automatically timed out. If you don't choose the right range, it can also affect performance because of excessive memory and garbage collection. Therefore, you need to set the range of objects correctly, and you should remove them immediately after you have finished using them.

Other methods:

Avoid string addition: using the + operation results in many temporary objects, because string is an immutable (immutable) object. The more the + operations, the more temporary objects will be created, resulting in a large system overhead. Use StringBuffer to replace + operations when you need strings added.

Avoiding the use of SYSTEM.OUT.PRINTLN:SYSTEM.OUT.PRINTLN is synchronous in disk I/O operations and can severely affect performance. Therefore, it is most possible to avoid the use of System.out.println. Despite the existence of powerful debugging tools, sometimes for tracking purposes, error handling, debugging programs, or use SYSTEM.OUT.PRINTLN. You should configure SYSTEM.OUT.PRINTLN to be used only in development and debugging situations. Using a static final Boolean variable, in production mode, configure False to avoid the use of System.out.println.

Servletoutputstream comparison printwriter: Using PrintWriter consumes some overhead because it is the output function that handles character streams. Therefore, PrintWriter should be used in environments that ensure character set conversion. In other words, you should use Servletoutputstream when you know that the servlet is returning only binary data, so you can eliminate the character conversion overhead when the servlet container does not have to handle character set conversions.

Summary

The purpose of this paper is to improve the performance of Java EE application System by improving the performance of Servlets and JSP pages through some practical operation and performance adjustment techniques. The next time you will be involved in performance tuning about EJBS (Enterprise JavaBeans), JMS (Java message Service), and JDBC (Java Database connectivity).

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.