After the mid-1990s, Java has also attracted some criticisms while winning. Winner is mainly the Java's cross-platform operability, that is, the so-called "Write Once, Run Anywhere". However, due to the performance of Java, there is still a lot of gaps compared to the Running efficiency, there is a lot of gaps. criticism. For the application of the server, the performance problem of Java seems to be unclear, so that some Java technology, such as JSP, Servlet, EJB, etc. are very obvious, so that some JAVA technology, such as JSP, servlet, ejb, etc. Large application, but in fact, Java's performance issues still exists on the server. Below I will discuss the performance and implementation efficiency of Java and improve Java performance. One. About the basic knowledge of performance 1. The definition of performance we need to understand the true meaning of "performance" before we discuss how to improve Java performance. We generally define the following five aspects as the criteria for judging performance. 1) Performance of the calculation --- Which algorithm performs performance is preferably 2) The allocation of the memory ---- The program needs to be assigned how much memory, the efficiency and performance of the runtime. 3) Start time ---- How much time it takes to start. 4) The scalability of the program ----- the performance of the program in the case of user load. 5) Performance's understanding ------ How can users recognize the performance of the program. For different applications, the requirements for performance are also different. For example, most applications take longer time at startup, thereby decreasing the starting time; the application of the server is usually allocated with large memory space, so the requirements for memory are also reduced. However, this is not that the performance of the two aspects can be ignored. Second, the performance of the algorithm is very important for applications that use business logic to transactional operations. In general, the requirements for the application will determine the priority to each performance. 2. How to improve Java performance improve Java performance, generally considering the following four main aspects: (1) Method and mode of programming and model A good design can improve the performance of the program, not only for Java, but also any Programming language. Because it makes full use of various resources, such as memory, CPU, cache, object buffer pools and multithreades, thereby designing high performance and scalable systems. Of course, in order to improve the performance of the program, it is more difficult to change the original design, but the importance of program performance is often higher than the design of the design. Therefore, there should be a good design model and method before the programming begins. (2) Environment of Java deployment. The environment of Java deployment refers to techniques for explaining and executing Java bytecles, usually as follows. That interpretation INSTRUCTIONS (Interpreter Technology), Technical time compiler (Just In Time Compilier Technology), adaptive optimization technique (Adaptive Optimization Technology), dynamic optimization, machine code is compiled ahead technique (Dynamic Optimization, Ahead Of Time Technology) And compile as machine code. These technologies are generally optimized by optimizing thread models, adjusting the size of the stack and stack to optimize Java performance. When considering the improvement of Java performance, you must first find bottlenenecks that affect Java performance. After confirming the rationality of the design, the Java deployment environment should be adjusted to improve the performance of the Java application by changing some parameters.
See Section 2 of the specific content. (3) The implementation of the Java application When discussing the performance issues of the application, most of the programmers will consider the code of the program, which is of course pair, when more important is to find bottleneck code affecting program performance. In order to find these bottleneck code, we generally use some auxiliary tools, such as JProbe, OptimizIT, VTune, and some analyzed tools such as Towerj Performance. These assisted tools can track the time consumed by each function or method in the application, thereby improving the performance of the program. (4) Hardware and operating systems In order to improve the performance of Java applications, use Fast CPUs and more memory, and believe that this is the only way to improve program performance, but this is not the case. Practical experience and facts have proven that only the application performance bottlenecks, there is appropriate way, such as design patterns, deployment, and operating system adjustments, is the most effective. 3. The usual performance bottleneck in the program. All applications have performance bottlenecks. In order to improve the performance of the application, it is necessary to reduce the bottleneck of the program as much as possible. The following is a performance bottleneck that often exists in the Java program.
[img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3a.gif [/ img] After you understand these bottlenecks, you can reduce these bottlenecks, thereby improving Java applications. Performance 4. Increases the performance of Java Program Performance In order to improve the performance of the Java program, you need to follow six steps below. a) Clear specific requirements for performance Before implementing a project, you must clarify the specific requirements for program performance, such as this application to support 5000 concurrent users, and the response time is within 5 seconds. But it also understands that the requirements for performance should not conflict with other requirements of the program. b) Understanding the performance of the current program You should understand the performance of your application with the gap between the performance requirements of the project. The usual indicator is the number of processing and response time in unit time, and sometimes the utilization of CPU and memory is compared. c) Find the program's performance bottleneck in order to find out the performance bottleneck in the program, usually use some analytics tools, such as TowerJ Application Performance Analyzer or VTune to see and analyze the time consumption of each element in the program stack, thus finding and correcting A bottleneck code with reduced performance, thereby increasing the performance of the program. These tools can also find potential issues such as excessive abnormalities, garbage collection. d) Take appropriate measures to improve performance After the bottleneck code that causes the program performance, we can use the four aspects of the improvement performance, namely design mode, Java code implementation, deployment of Java's environment and Operating systems to improve the performance of the application. The details will be described in detail in the following. e) Improvement of amendments only to improve performance only one aspect that may cause performance reduction, and then the performance of the program is improved, and it should not change multiple aspects, because you will not know Which aspect change has improved the performance of the program, which is not, that is, the program bottleneck is not known. f) Return to step c, continue to work similar to the performance, which has been achieved. Two. When the Java deployment environment and compilation technology develops Java applications, first compile Java source programs as unrelated to the platform. These bytes can be performed by various JVM-based technologies. These technologies are mainly divided into two large categories. That is, a technique based on the interpretation and technique based on the pre-compiled as local code. The schematic is as follows:
[img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3b.gif [/ IMG] Specific class five categories: a) Interpretation of the designation technology drawings and execution processes are as follows: [img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3c.gif [/ img] Java compiler first compiles the Java source file as a bytecode. These bytes are the Java Virtual Machine (JVM) is the machine's instruction code. Then, Java's interpreter continuous loops takes out the bytecode and executes. The advantage of this is that the cross-platform of the Java language can be implemented, and the generated bytecode is also compacted. Some of Java, such as security, dynamics have to be kept; but the disadvantage is that the province's generated bytecode is not optimized, and the speed is slower than all compiled local code. b) Timely Compilation Technology (Just In Time) Timely Compilation Technology is to resolve the instruction interpretation technology is relatively low, and the speed is relatively slow, and the structural drawings are shown below.
[img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3d.gif [/ img] Its main change is before the Java program is executed, and the JIT compiler compiles the Java's bytecode as Machine code. Thereby directly executing the machine code directly at runtime without using the bytecode. At the same time, the code also has been partially optimized. The advantage of this is that it greatly improves the performance of the Java program. At the same time, since the results of the compilation are not stored in the program running, the time to store the loader is also saved; the disadvantage is that the JIT compiler is optimized to all the code, so it is also a lot of time. IBM and Sun provide relevant JIT products. c) Adaptive Optimization Technology (Adaptive Optimization Technology) is not optimized for all bytecodes compared to JIT technology. It tracks the procedure of the program run, thus discovering the code that needs to be optimized, and dynamically optimized the code. For optimized code, take 80/20 strategies. In theory, the longer the program is running, the more optimized the code. The structural diagrams are as follows: [img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3e.gif [/ img] It advantages It is that adaptive optimization technology makes full use of the information execution time, issue The program's performance bottleneck, thereby improving the performance of the program; its disadvantage is that improper choice is to optimize, and reduce the performance of the program. Its main products are IBM, Sun's Hotspot. D) Dynamic Optimization, Ahead Of Time Dynamic Optimization, Ahead Of Time Dynamic optimization technology fully utilizes Java source compilation, bytecode compilation, dynamic compilation and static compilation Technology. The original code or bytecode of Java is input, and the output is a mixture of highly optimized executable code and a dynamic library (a DLL file in Window, and the shared library in Unix is a shared library .a .so file). The structure is as follows:
[img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_3f.gif [/ img] Its advantage is that it can greatly improve the performance of the program; the disadvantage is to destroy Java portability, and Java's security has brought certain hidden dangers. Its main product is TowerJ3.0.
three. Optimize the Java program design and encoding, improve some of the methods of Java program performance. Find the bottleneck in the program by using some of the previously described auxiliary tools, and then optimize the code of the bottleneck portion. There are generally two options: optimizing code or changing design methods. We generally choose the latter, because you don't call the following code to improve program performance than call some optimized code. And a well-designed program can streamline the code to improve performance. Some methods and techniques that are often used in the design and encoding of the Java program, and some methods and techniques that are often used in the design and encoding of the Java program. 1. Adjustment of the generation and size of the object. A common problem in the Java program is that there is no function provided by the Java language itself, which often generates a large number of objects (or instances). Since the system not only takes time to generate an object, it may still take time to take the time to garbage recycling and processing. Therefore, excessive objects will have a big impact on the performance of the program. Example 1: About String, StringBuffer, , and Append Java languages provide operations for String type variables. However, if not used, it will affect the performance of the program. As of the following statement: string name = new string ("HuangWeifeng"); System.out.Println (Name "Is My Name"); seemingly very streamlined, it is not the case. In order to generate binary code, the following steps and operations are processed. (1) Generate a new string new string (STR_1); (2) Copy the string. (3) Load the string constant "HuangWeifeng"; (4) Call the string of the architecture; (5) Save the string into an array (starting from position 0) (6) from Java.io The static OUT variable (7) generates a new string buffer variable in the .printStream class New StringBuffer (STR_BUF_1); (8) Copy the string buffer variable (9) Call string buffer (constructor); (10); (10) ) Save the string buffer to an array (starting from position 1) (11) Taking STR_1 as a parameter, calling the Append method in the string buffer class. (12) Loading the string of the constant "IS my name"; (13) Taking STR_3 as the parameter, call the Append method in the string buffer. (14) Execute the toString command for STR_BUF_1. (15) Call the PrintLn method in the OUT variable, output the result. It can be seen that the two lines of simple code generates STR_1, STR_2, STR_3, STR_4, and STR_BUF_1 five object variables. Examples of these generated classes are generally stored in the heap. Piles are initialized for all classes, classes of all classes, while also calling an extremely super-class architecture. These operations are very consumed system resources. Therefore, it is necessary to limit the generation of objects. After modification, the above code can be replaced with the following code.
StringBuffer name = new stringbuffer; system.out.println ("is my name."). TOSTRING ()); the system will perform the following operations. (1) Generate a new string buffer variable new stringbuffer (STR_BUF_1); (2) Copy the string buffer variable (3) load string constant "huangweifeng" (STR_1); (4) call string buffer architecture ( Constructor); (5) Save the string buffer to an array (starting from position 1) (6) Get static OUT variable from the java.io.printStream class to load STR_BUF_1; (8) loading string often " Is my name "(STR_2); (9) Call the Append method in the StringBuffer instance with STR_2. (10) Execute the toString command for STR_BUF_1. (STR_3) (11) Call the PrintLn method in the OUT variable, output the result. It can be seen that the improved code only generates four object variables: STR_1, STR_2, STR_3 and STR_BUF_1. You may feel that less generation of an object will not increase the performance of the program. However, the execution speed of the code segment 2 below will be twice the code segment 1. Since the code segment 1 generates eight objects, the code segment 2 generates only four objects. Code segment 1: String name = new stringbuffer ("huangweifeng"); name = "is my"; name = "name"; code segment 2: stringbuffer name = new stringbuffer ("HuangWeifeng"); name.Append ("is my "); Name.append (" name. "). TOSTRING (); therefore, fully utilizing the library function provided by Java to optimize the program, is very important to improve the performance of the Java program. The attention points mainly have the following aspects (1) Use static class variables if possible, if the variables in the class do not change with his instance, you can define static variables so that all of his instances share this variable. Example: Public class foo {someObject SO = New someobject ();} You can define as: public class foo {static homeObject so = new someobject ();} (2) Do not make too much changes to generated objects. For some classes (such as: String class), prefer to regenerate a new object instance without modifying the generated object instance. Example: String name = "huang"; name = "wei"; name = "feng"; the above code generates three String type object instances. The first two immediately need system for garbage collection. If you want to connect to a string, performance will be worse. Because the system will not generate more temporary variables for this. As shown in the first example. (3) When the object is generated, many classes to be assigned to it rationally and the size in Java have its default spatial allocation size. For StringBuffer classes, the default assignment space size is 16 characters. If the size of the StringBuffer is not 16 characters in the program, the correct initialization must be performed. (4) Avoid generating objects or variables shorter or shorter life cycle.
For this case, an object buffer pool is defined. It is to manage a smaller cost of managing a target buffer pool than frequent generation and recycling objects. (5) Initialization only within the target scope. Java allows you to define and initialize the object anywhere in your code. In this way, it can be initialized only within the range of the object. Thereby saving the overhead of the system. Example: SomeObject SO = New SomeObject (); if (x == 1) THEN {foo = SO.GETXX ();} can be modified to: if (x == 1) Then {SomeObject SO = New SomeObject (); foo = sol.getxx ();} 2. Try / catch in an exception (Exception) Java language provides TRY / CATCH to facilitate user capture exceptions to process abnormalities. But if you use improper use, it will also affect the performance of the Java program. Therefore, pay attention to the following two points. (1) Avoid logic to the application using TRY / CATCH If you can use the IF, while, etc. can be handled, then do not use the TRY / CATCH statement (2) to reuse an exception to process the exception, Reuse the existing anomaly objects as much as possible. Those in the abnormal process, generating an abnormal object to consume most of the time. 3. Threading A high-performance application usually uses threads. Because threads make full use of the resources of the system. In other threads, the program can continue to process and run because of the other threads waiting for the hard disk or network read and write. However, it is used to use improper use and will affect the performance of the program. Example 2: Correct use of the Vector class Vector is mainly used to save various types of objects (including the same type and different types of objects). However, in some cases, use the performance of the program to bring performance. This is mainly determined by the two features of the VECTOR class. First, Vector provides thread safety protection features. Even many methods in the Vector class synchronize. But if you have confirmed that your application is a single thread, the synchronization of these methods is completely unnecessary. Second, when you look for various objects stored, it often spends a lot of time to match the type. These matches are completely unnecessary when these objects are in the same type.
Therefore, it is necessary to design a single-threaded, saving a specific type object class or a collection to replace the vector class. The program used to replace is as follows: public class stringvector {private string [] data; private int count; public; StringVector () {this (10); // default size is 10} public stringvector (int initialsize) {data = new string [initialsize];} public void add (string str) {// ignore null strings if (string String Strings if (string String Strings if (Str == null) {return;} ensureCapacity (count 1); data [count ] = str;} private void ensureCapacity (int minCapacity) {int oldCapacity = data.length; if (minCapacity> oldCapacity) {String oldData [] = data; INT newcapacity = Oldcapacity * 2; Data = new string [newcapacity]; System.Arraycopy (OldData, 0, DATA, 0, Count);}}} PUBLIC VOID REMOVE (STRING STR) {if (str == null) {Return / / ignore null str} for (int i = 0; i
The procedures for test are as follows: import java.util.vector; public class testcollection {public static void main (string args []) {testcollection collect = new testCollection (); if (args.length == 0 ) {System.Out.println ("usage: java testcollection); system.exit (1);} if (args [0] .Equals (" vector ") {Vector store = new vector ); long start = system.currenttimemillis (); for (int i = 0; i <1000000; i ) {store.addelement ("string");} long finish = system.currenttimemillis (); system.out.println (Finish-start); start = system.currenttimemillis (); for (int i = 0; i <1000000; i ) {string result = (string) Store.Elementat (i);} finish = system.currenttimemillis () System.out.Println (FINISH-START));} else if (args [0] .Equals ("stringvector")) {stringVector store = new stringVector (); long start = system.currenttimemillis (); for INT i = 0; i <1000000; i ) {store.add ("string");} long finish = system.currenttimemillis (); system.out.println; s TART = system.currenttimemillis (); for (int i = 0; i <1000000; i ) {string result = store.getstringat (i);} finish = system.currenttimemillis (); system.out.println ((Finish- START));}}} / * * * * * * * * * * TestCollection.java * * * * * * * * * * * * * * * * / Test results are as follows ( Suppose the standard time is 1, the smaller performance, the better:
[img] http://www.computerworld.com.cn/htm/app/aprog/01_7_9_4.gif [/ img] About thread operation, pay attention to the following aspects. (1) Prevent excessive synchronization As shown above, unnecessary synchronization often causes a decline in program performance. Therefore, if the program is a single thread, you must not use synchronization. (2) Synchronous method instead of synchronizing the entire code segment to synchronize a method or function to synchronize the entire code segment. (3) Increase the mechanism for each object using multiple "lock". Generally, each object has only one "lock", which indicates that "dead lock" occurs if two threads perform two different synchronization methods of an object. Even if these two methods do not share any resources. To avoid this problem, you can implement "multi-lock" mechanisms to an object. As follows: class foo {private static int var1; private static Object lock1 = new Object (); private static int var2; private static Object lock2 = new Object (); public static void increment1 () {synchronized (lock1) {var1 }}} public static void increment2 () {synchronized (lock2) {var2 ;}}} 4. Input and output (I / O) input and output include many aspects, but involving the most is the read and write operations of the hard disk, network, or database. For read and write operations, it is divided into cache and no cache; for the operation of the database, there can be multiple types of JDBC drivers to choose. But no matter what, it will affect the performance of the program. Therefore, it is necessary to pay attention to the following: (1) Use the input and output buffer as much as possible to use the cache. However, if you want to refresh the cache, it is recommended not to use a cache. (2) Output stream and Unicode strings When using Output Stream and Unicode strings, the WRITE class has a big overhead. Because it is to implement Unicode to byte (byte) conversion. Therefore, if possible, transition is implemented before using the Write class, or use the OutputStream class instead of the Writer class. (3) When serialization is serialized as a class or object when serialization, for those atomic or reconstructed powdery, it is to recognize the TRANSIENT type. This will not be serialized each time. If these serialized objects are transmitted over the network, this small change has great improvement in performance. (4) Using Cache For objects or data that are often used and unclear, you can store it in a cache. This will increase the speed of access. This is especially important for the result set returned from the database. (5) Provide four ways to access the database using the JDBC Drive (Driver) Java Java. There are two kinds of JDBC drivers. One is a local drive out of Java; the other is a complete Java drive. Which of the specific use of the Java deployment itself is determined. 5. Some other experiences and techniques (1) Use local variables (2) to avoid setting or calling variables in the same class during the same class. (3) Avoid using System.ArrayCopy when copying a large amount of data using Static, Final, Private, and other keywords (5) as possible using Static, Final, Private, and so on. ()command.
Public Static String Replace (String Value, String Key, String ReplaceValue) {if (value == null || key == null || replacevalue == null) {Return Value;}
INT POS = Value.indexof (key);
IF (POS <0) {Return Value;
INT length = value.length (); int start = pos; int end = pos key.length ();
IF (length == key.length ()) {value = replacevalue;
} else if (end == length) {value = value.substring (0, start) ReplaceValue;
} else {value = value.substring (0, start) ReplaceValue Replace (Value.substring (end), key, replacevalue);}
Return Value;} It is found that there is no, the previous IFSE IF can be operated as the last ELSE, but why, because it may be necessary to perform a Replace recursive call, this is seen from the Validator source code, in one paragraph: IF: IF ("LOG.DEBUGENABLED ()) {log.debug (" Looking for action instance for class " classname);} Why is it necessary to determine whether it is debug, not if it is configured as debug? Remember, the information will not output, but "looking for action instance for class" classname This statement will always be executed, and a simple Boolean judgment can reduce the operation of string.
Therefore, optimize performance, can't rely on long, but also from small things, discovery from the actual application and the seniors code, summary
To remember try to cache, such as code: protected method getMethod (String name) throws nosuchmethodeXception {
Synchronized (Method) {Method Method = (Method) Methods.get (name); if (Method == Null) {Method = Clazz.getMethod (Name, Types); Methods.Put (Name, Method);} Return (Method) );} This is the code that uses reflection method in Struts.
In the actual development of J2EE, it is best not to store large objects in Request, Session, but should be stored in small objects, and should be avoided by the List, not only the code is not good, it is difficult to understand. Because some servers use the information in the session to be stored in the database, if the WebLogic is configured to store the information or the database, if you store the big object, then after you modify a property, you call SetAttribute operations, At this point, the server stores the big object is a very time time. If it is released in the cluster, then the content stored in the store is too much, and the synchronization in the cluster is also very time consuming.
Curve only if it is necessary to make a cache. . Instead, "To remember the tricks" With the development of JVM, the current JVM is generally used by the independent garbage collection mechanism, which will be divided into small-scale garbage collection (only less CPU time), large scale The garbage collection (occupying a large number of CPU time) So best is instantiated a subject soon, after reference expires, it will be collected immediately if you do unnecessary cache, the JVM must spend a lot of CPU time in collecting cached Stack of objects..
This is true, of course, if it is not necessary, it is sure that it is not necessary to cache, but as I have passed above, I forgot to come out from Struts or Validator, I want this distributed application, on the network There may be many people in calling, and Struts uses the front-end controller, then the cache this class is then very necessary, because the reflection is a relatively good operation, then if each request is It is definitely the low efficiency of the Method object.
I want to have the above cache generally the maximum use is in the distributed, and these instances are shared by all users. If it is a single user, then the actual meaning is still not big.
/ *** The same name is the same * / public boolean equals (object object) {Return Object InstanceOf Column && Equals
/ *** The same name is the same * @Param column * @ Return * / public boolean equals (column column) {if (null == column) Return false; if (this == column) Return TRUE;
Return name.equals (color);} This code is good, the previous implementation is: if (Object InstanceOf Column) {Column Column = (Column) Object; Column ....} But if the forefront is written , Then the step JVM of judgment type is to determine whether the efficiency is improved, and it is 6 times that is 600,000 times.
/ * * Created on 2004-12-17 * * Todo to change the Template for this generated file go to * window - preferences - java - code style - code templates * / package temp; / ** * @Author xinli * * Todo TO CHANGE THE TEMPLATE for This Generated Type Comment Go To * WINDOW - Preferences - Java - Code Style - Code Templates * / Public Class Test {
Public static void main (string [] args) {test test = new test (); a a = new b (); b = (b) a; test.a (b); test.a (a);
C c = new d (); D = (d) C; test.c (c); test.c (d);} public void A (a a) {system.out.println ("a) ");} public void A (b) {system.out.println (" a (b) ");} public void c (c) {system.out.println (" c) ");} Public void c (d) {system.out.println ("c (d)");}} Class A {
} Class B Extends a {
Interface c {
} Class D Implements C {
} The result is: A (b) A (a) c (c) c (d) How does it have no overloading in inheritance relationship? I have been in Java for more than two years. I found it today.
Recommended article JSP / servlet application optimized eight law [reposted] original http://blog.9cbs.net/irchive/2004/12/23/226958.aspx
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. Technical 1: Cache Data Server in the httpservletinit () method will then call the servlet's init () method before the servlet instance is created. 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: publicclassControllerServletExtendShttpservlet {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: Disable servlet and JSP automatic load function 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 HttpSesions 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 to use httpsession in the JSP page, in order to save performance overhead, use the following page instructions to use the following page instructions to automatically create httpsession objects: <% @pagesession = "false"%>
1) Don't store large object maps in httpsession: If you use 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.