Is your J2EE app running very slow? Can they bear the continuous increase in access? This article tells the development of performance optimization techniques for developing high performance, high-elastic JSP pages and servlets. It means that it is to establish as fast and adaptable users and their requests. In this article, I will lead you to learn and have confirmed performance adjustment technology, which will greatly improve your performance of your servlet and JSP pages, which in turn enhances the performance of J2EE. The part of these technologies is used to development stages, such as design and coding stages. Another part of the technology is related to the configuration.
Technology 1: Cache data in httpservletinit () method
The server will call the servlet's init () method before creating a servlet instance and the servlet process. This method is only called once in the life cycle of the servlet. In order to improve performance, slow storage in init () or complete expensive operation 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. Every time you call SQL, you will use JNDI to find DataSource to be very expensive and seriously affecting the performance of the application. Servlet's init () method can be used to get DataSource and cache it to reuse after it:
PublicclassControllerServletExtendshtpservlet {privatejavax.sql.datasourcetestds = null;
publicvoidinit (ServletConfigconfig) throwsServletException {super.init (config); Contextctx = null; try {ctx = newInitialContext (); testDS = (javax.sql.DataSource) ctx.lookup ( "jdbc / testDS");} catch (NamingExceptionne) {ne.printStackTrace ();} catch (exceptione) {E.PrintStackTrace ();}}
Publicjavax.sql.datasourcegetTestDs () {ReturnTestDs;} ...
Technology 2: Disabling the automatic load function of servlet and JSP
When you modify the servlet / JSP each time, you will have to restart the server. This feature is considered to be very useful during the development phase due to the reduction in the development time of the automatic load function. However, it is very expensive during operation; servlet / JSP causes poor performance due to unnecessary loads, increasing the loader's burden. Similarly, this will make your application that cannot be worried about the class that has been loaded with a class loader and the class loaded with the current type loader. Therefore, in the operating environment, the automatic load function of Servlet / JSP is turned off in order to obtain better performance.
Technology 3: Control HttpSession
Many applications require a series of client requests, so they can be associated with each other. Since the HTTP protocol is stateless, the Web-based application needs to be responsible for maintaining such a status called Session. To support applications that must maintain status, JavaServlet technology provides an API that manages session and allows multiple mechanisms to implement session. The HttpSession object plays Session, but uses it needs cost. Whenever HttpSession is used and rewritten, it is read by servlet. You can improve performance by using the following technique: l Do not create a default httpsession in the JSP page: By default, the JSP page creates httpsession. If you don't have HTTPSESSION in the JSP page, in order to save performance overhead, use the following page instructions using the following page instructions to avoid automatically create httpsession objects: <% @pagesession = "false"%> 1) Do not store large object maps in httpsession: if You use the data as a large object map in httpsession, the application server will have to handle the entire HTTPSession object each time. This will force Java serialization and increase computing overhead. Due to serialization overhead, with the increase in data objects stored in the httpsession object, the system throughput will decline.
2) Release HTTPSESSION after use: When not using HttpSession, use the httpsession.invalidate () method to fail.
3) Set the timeout value: A servlet engine has a default timeout value. If you don't delete sessions or always use the session to timeout, the servlet engine will remove the session from memory. Due to the overhead of memory and garbage collection, the larger the timeout value of the session, the greater the impact on the elasticity and performance of the system. Try to set the timeout value of the session as low as possible.
Technology 4: Compression using GZIP
Compression is the process of deleting redundant information, describing your information with as little space as possible. Use GZIP (GNUZIP) to compress files to effectively reduce the time to download the HTML file. The smaller your information, the faster it is sent. So if you compress the content generated by your web application, it reaches the user and display the faster the speed on the user screen. Not any browser supports Gzip compression, but checks if a browser supports it and sends Gzip compressed content to a browser. The code segment below illustrates how to send compressed content.
PublicvoidDoGet (httpservletRequestRequest, httpservletResponseresponse) throwsioException, servletexception {
OutputStreamout = NULL
//Checktheaccepting-encodingheaderfromthehtpRequest.//iftheheaderincludesgzip, choosegzip.//iftheheaderincludescompress, choosezip.//otherwisechoosenocompression.
StringeEncoding = Request.getHeader ("Accept-encoding");
if (encoding = null && encoding.indexOf ( "gzip") = - 1!!) {response.setHeader ( "Content-Encoding", "gzip"); out = newGZIPOutputStream (response.getOutputStream ());} elseif (encoding! = null && encoding.indexOf ( "compress") = - 1) {response.setHeader ( "Content-Encoding", "compress"); out = newZIPOutputStream (response.getOutputStream ());}! else {out = response.getOutputStream ( );} ...
Technology 5: Don't use SingleThreadModel
SingleThreadModel guarantees that only a request is processed once 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 lot of system overhead. If you need to resolve thread security issues, use other ways to replace this interface. SingleThreadModel is no longer advocated in servlet2.4.
Technology 6: Using thread pool
The servlet engine creates a separate thread for each request, assigns the thread to the service () method, and then delete the thread after the service () method is executed. By default, the servlet engine may create a new thread for each request. This default behavior reduces the performance of the system due to the cost of creating and deleting threads, so this default behavior reduces the performance of the system. We can use thread pools to improve performance. According to the expected quantity, configure a thread pool, set the minimum and maximum values of the number of threads in the thread pool, and the minimum and maximum growth. At first, the Servlet engine created a thread pool equal to the number of minimum threads in the configuration. The servlet engine then assigns a thread in the pool to a request instead of creating a new thread every time, after completing the operation, the servlet engine puts the thread back to the thread pool. With thread pools, performance can be significantly improved. If necessary, more threads can be created depending on the maximum number of threads and growth.
Technology 7: Select the correct included mechanism
In the JSP page, there are two middle ways can include files: including instructions (<% @ includefile = "Test.jsp"%>) and include action (
Technology 8: Use the appropriate range in the useBean action
One of the most powerful ways using JSP pages is to work with JavaBean components. JavaBean can be embedded in the JSP page using the
For example, if you need an object dedicated to some requests, you set the range to sessions, then that object will remain in memory after the request is over. It will always remain in-memory unless you explicit it clearly from memory, so that the session is invalid or session timeout. If you don't have the right range properties, the overhead of memory and garbage will affect performance. Therefore, the appropriate range is set for the object and remove it immediately after using them.
Miscellaneous technology
1) Avoid string connections: Since the String object is an unmattered object, use the " " operator will result in a large number of zero. The more " " you are using, the more zero output, which will affect performance. When you need to connect a string, use StringBuffer instead of " ".
2) Avoid using system.out.println: system.out.println to synchronize processing disk input / output, which greatly reduces system throughput. Avoid using System.out.Println as much as possible. Although there are many mature debugging tools that can be used, but sometimes system.out.println is still useful for tracking, or debugging. You should configure system.out.println to open it only in the error and debug phase. Using the FinalBoolean type variable, when configured to False, the optimized check and perform the tracking output during the compile phase.
3) ServletOutputStream and PrintWriter Comparison: Due to the character output stream and the data encodes the data into bytes, using PrintWriter introduces small performance overhead. Therefore, PrintWriter should be used correctly after all character sets are finished correctly. On the other hand, when you know that your servlet returns binary data, use servletoutputstream, because the servlet container does not encode binary data so you can eliminate character set conversion overhead.
to sum up
The purpose of this article is to show you some practical and confirmed performance optimization techniques for increasing Servlet and JSP performance, which will increase your integral performance of your J2EE application. The next step should observe the performance adjustment of other related technologies, such as EJB, JMS, and JDBC.