Performance Optimization of Java
For server-side applications, because not related to interface design and procedures for the resumption of frequent, Java's performance problems may seem less obvious, so a number of Java technologies such as JSP, Servlet, EJB, such as server-side programming in the areas a lot of applications, but in fact, Java's performance problems still exist at the server side. I will be the following four areas to discuss the implementation of Java performance and efficiency, and improve the performance of a number of Java methods.
1. Basic knowledge about performance
1. The definition of performance
When we discuss how to improve the performance of Java, we need to understand the "performance" of the true meaning. Our general definition of the following five areas as performance evaluation criteria.
1) ---- performance computing algorithm for the implementation of which the best performance
2) the allocation of memory is required to ---- the number of memory distribution, run-time efficiency and the highest performance.
3) start the proceedings of the time ---- how much time required.
4) procedures ----- procedures scalability overload in the user's performance under the circumstances.
5) Performance ------ Know how to recognize a user to program performance.
For different applications, performance requirements are also different. For example, most applications at startup required a longer period of time, thus the request for start-up time is reduced; server-side applications usually have a larger distribution of memory space, so memory requirements were also reduced. However, this is not the performance of these two aspects can be ignored. Secondly, the algorithm performance for those who put business logic into the business applications in terms of operation is very important. Generally speaking, the requirements of the applications will determine the performance of each priority class.
2. How can we improve the performance of JAVA
JAVA improve performance, in general consider the following four main areas:
(1) program design methods and models
A good design can improve the performance of the procedure, which applies not only to JAVA, it also applies to any programming language. Because it makes full use of various resources, such as memory, CPU, cache, buffer pool object and multi-threaded, so the design of high-performance and scalable systems and strong.
Of course, in order to improve the performance of the procedure to change the original design is more difficult, but the importance of performance usually higher than on the changes brought about by design. Thus, in programming before the start there should be a good design model and methods.
(2) JAVA deployment environment.
JAVA deployment environment refers to the interpretation and implementation of JAVA byte-code technology, generally have the following five. That is, to explain technical instructions (Interpreter Technology), the technology in time compiler (Just In Time Compilier Technology), adaptive optimization technology (Adaptive Optimization Technology), dynamic optimization, advanced compiler technology for the binary (Dynamic Optimization, Ahead Of Time Technology) and compiler technology for the binary (Translator Technology).
These technologies are generally threaded through optimization models, adjust the size of heap and stack to optimize the performance of JAVA. In considering the performance of JAVA improve, the first to find performance bottlenecks in JAVA impact (BottleNecks), confirming the reasonableness of the design, you should adjust deployment JAVA environment, by changing some parameters to improve the performance of JAVA applications. See section II, the specific content.
(3) JAVA application implementation
When discussing the application performance problem, most programmers will consider the procedure code, which of course is, when is more important is to find performance bottlenecks impact code. Code in order to find these bottlenecks, we will generally use some tool to help, such as Jprobe, Optimizit, Vtune as well as some analysis tools such as such as TowerJ Performance. These instrument-assisted applications to track the implementation of each function or method of the time consumed, thus improving the performance of the procedure.
(4) hardware and operating system
JAVA in order to improve application performance, and quickly adopt the CPU and more memory, and that improve performance This is the only way, but is not the case. Practical experience and facts have proven that only by the application performance bottlenecks, which may take the appropriate methods, such as the design model, deployment environment, adjust the operating system, is the most effective.
3. Procedures in the performance bottlenecks usually.
All applications are performance bottlenecks exist, in order to improve application performance, it is necessary to process as much as possible to reduce the bottleneck. The following is a JAVA program always at the performance bottlenecks exist.
Learn the bottleneck, you can have targeted to reduce these bottlenecks in order to improve the performance of JAVA applications
4. Improve performance steps JAVA
JAVA in order to improve the performance of procedures, required to follow the six steps are as follows.
a) clear the specific requirements of the performance
Prior to the implementation of a project, the project must be clear about the specific requirements of performance, such as: the application to support 5000 concurrent users and response time to 5 seconds. But at the same time to understand the requirements for the performance of procedures should not be with the other requirements of the conflict.
b) know the current process performance
You know you should be the performance of the application requirements with the project performance gap. Units are usually the target of the treatment time and response time of a few, and sometimes compare the utilization of CPU and memory.
c) the procedure to find the performance bottleneck
Process in order to find performance bottlenecks, usually using some analytical tools, such as: TowerJ Application Performance Analyzer or VTune View and analytical procedures to the various elements of the stack time-consuming and thus the right to find and correct performance bottlenecks caused by code improve the performance of the procedure. These tools also found, such as too much exception handling, garbage collection, such as potential problems.
d) take appropriate measures to improve performance
Found a decrease in performance caused by bottlenecks in code, can be used in front of us on the introduction of improved performance over the four areas, namely design patterns, JAVA code implementation, deployment and operating system JAVA environment to improve application performance. The specific details of the content below for details.
e) only changes in one aspect to improve performance
Probably caused by a change in only one aspect of performance, and then observe whether the performance of procedures has increased, rather than a change in many aspects, because it did not know in the end you will be changes which improve the performance of the procedure, which aspects of No, that is, the procedure should not know where the bottleneck.
f) return to step c, to continue to make a similar job, the performance has been far below the required standards.
2. . JAVA deployment environment and compiler technology
JAVA application development, first of all, put the source code compiler for JAVA platform-independent byte code. These byte-code can be based on the JVM implementation of the technology. These techniques are mainly classified into two major categories. Explained based on the technology and advanced compiler-based technology for the local code. Its schematic diagram is as follows:
Concrete can be divided into the following five categories:
a) explain the directives of technical
Its structure and implementation of the process is as follows:
First of all, the compiler JAVA put JAVA source file for byte-code compiler. These byte-code for the JAVA Virtual Machine (JVM) is the machine in terms of script. And, JAVA interpreter of the cycle of constantly removed byte-code interpretation and implementation.
The advantage of doing so can achieve cross-platform JAVA language, at the same time generated more compact byte code. Some of the advantages of JAVA, such as security, had to remain dynamic; but the disadvantage is the province of bytecode generated little or no optimization, with all the compiled code compared to the local well, more slowly.
b) in time compiler technology (Just In Time)
Compiler technology and timely instructions are explained in order to solve the technical efficiency is relatively low, relatively slow speed of the circumstances, and its structure are as follows.
The main changes are in the process before the execution of JAVA and JIT compiler JAVA put the byte-code compiler for the binary. At run-time procedures in order to direct the implementation of binary, rather than on byte code interpretation. At the same time, also part of the code optimization.
The advantage of doing so greatly improve the performance of the JAVA program. At the same time, because the results of the compiler does not run in the inter-preservation, thus saving storage space of time loader; disadvantage because JIT compiler are all want to optimize the code, and therefore a lot of wasted time.
IBM and SUN have provided a JIT-related products.
c) adaptive optimization technology (Adaptive Optimization Technology)
Compared with the JIT technology, adaptive technology is not optimized for all the byte-code optimization. It will track the process into a process running, which was found necessary to optimize the code, dynamic code optimization. To optimize the code, take the 80/20 strategy. In theory, the program runs longer, more optimized code. Its structure is as follows:
The advantage of adaptive optimization technology makes full use of information at the time of program execution, the performance bottleneck issue process, in order to improve the performance of the procedure; Optimize its shortcomings are conducting improper selection may be, the lower the performance of the procedure.
Its main products IBM, SUN's HotSpot.
d) dynamic optimization, advanced compiler technology for the binary (Dynamic Optimization, Ahead Of Time)
Dynamic optimization techniques take full advantage of the JAVA source code compiler, byte-code compiler, dynamic and static compiler compiler technology. Its input the original JAVA code or byte code, and output are highly optimized executable code and a dynamic library to the mixed (Window is a DLL file, UNIX is a shared library. A. So files). Its structure is as follows:
The advantage is to greatly improve the performance of the procedure; destroy the disadvantage is portability of JAVA, JAVA security also brings a certain degree of risk.
Its main products are TowerJ3.0.
Three . Optimize JAVA programming and coding, JAVA enhance performance of some methods.
Through the use of some of the previous introduction of the auxiliary instrument had to find process bottlenecks, and then can be part of the bottlenecks to optimize the code. There are two programs: the optimization of the code or change the design. We usually select the latter, not because the following code to call than to call some code optimization can improve the performance of the procedure. A well-designed program can streamline the code, so as to enhance the performance.
The following will provide some of the JAVA program design and coding in JAVA in order to be able to improve the performance of the procedure, and often used in a number of methods and techniques.
1. Object the size of the generation and adjust.
JAVA programming a universal problem is that there is no good use of JAVA language function itself, which usually generates a large number of objects (or instances). To spend time not only because of the system to generate the target may need to spend time on these subjects and deal with garbage collection. Therefore, the object will be generated too much to process a great deal of impact on performance.
Example 1: The String, StringBuffer, + and append
JAVA language provides for the operation of String type variable. However, if used improperly, could impact the performance of the procedure. Such as the following statement:
String name = new String ( "HuangWeiFeng");
System.out.println (name + "is my name");
Appears to have been very brief, but in fact not the case. In order to generate a binary code, it is necessary to carry out the following steps and operations.
(1) create a new string of new String (STR_1);
(2) a copy of the string.
(3) to load the string constant "HuangWeiFeng" (STR_2);
(4) device called the framework of string (Constructor);
(5) to preserve the string to the array (from the start location of 0)
(6) from class java.io.PrintStream be out static variables
(7) generate a new string buffer variable new StringBuffer (STR_BUF_1);
(8) a copy of the string buffer variable
(9) framework called string buffer device (Constructor);
(10) to preserve the string buffer to the array (from one start position)
(11) to STR_1 for the parameters, called the string buffer (StringBuffer) method append category.
(12) to load the string constant "is my name" (STR_3);
(13) to STR_3 for the parameters, called the string buffer (StringBuffer) method append category.
(14) for the implementation of toString order STR_BUF_1.
(15) calls out the println method of the variable, the output results.
This can be seen that these two simple lines of code, it generated STR_1, STR_2, STR_3, STR_4 and five STR_BUF_1 object variable. These generated classes are generally kept in the heap. Reactor for all types of super-class to initialize class instances, but also calls for each type of extreme ultra-framework-type device. These operations are the consumption of system resources. Therefore, to limit the generation of the object is completely necessary.
Modified, the code above can be used to replace the code is as follows.
StringBuffer name = new StringBuffer ( "HuangWeiFeng");
System.out.println (name.append ( "is my name."). ToString ());
System operation will be carried out as follows.
(1) create a new string buffer variable new StringBuffer (STR_BUF_1);
(2) a copy of the string buffer variable
(3) to load the string constant "HuangWeiFeng" (STR_1);
(4) call the framework of string buffer device (Constructor);
(5) to preserve the string buffer to the array (from one start position)
(6) from class java.io.PrintStream be out static variables
(7) load STR_BUF_1;
(8) to load the string constant "is my name" (STR_2);
(9) to STR_2 for the parameters, called the string buffer (StringBuffer) method append an example of.
(10) for the implementation of toString order STR_BUF_1. (STR_3)
(11) calls out the println method of the variable, the output results.
This can be seen that improved only after the code to generate the four target variables: STR_1, STR_2, STR_3 and STR_BUF_1. You may feel less will not generate an object program has greatly improved performance. However, the following code segment 2 of the implementation of the speed of the code segment will be one of the 2-fold. Since the code segment to generate one of eight targets, and the code segment to generate two to 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, the full utilization of available JAVA library functions to optimize procedures, improve the performance of JAVA procedures are very important. Its attention to the following major areas;
(1) as far as possible the use of static variables (Static Class Variables)
If the class variables do not change an example of him, it can be defined as static variables so that all his examples of the variables are shared.
Example:
public class foo
(
SomeObject so = new SomeObject ();
)
Can be defined as:
public class foo
(
static SomeObject so = new SomeObject ();
)
(2) not to have been generated for the object to change too much.
For some categories (such as: String type) terms, would prefer to re-generate a new object instance, rather than modify the object instance has been generated.
Example:
String name = "Huang";
name = "Wei";
name = "Feng";
Code generation of the above-mentioned three types of String object instance. Immediately before the required two garbage recycling system. If you want to connect to the string of operations, performance will be worse. To this end because the system will not be allowed to generate a temporary variable more. As shown in Example 1.
(3) to generate object, it is necessary to give it a reasonable distribution of space and the size of
JAVA in a lot of categories has its default size of the space distribution. For Class StringBuffer, the default size of the distribution are 16 characters. If in the procedure room for the use of StringBuffer size is not 16 characters, then the right must be initialized.
(4) not to use or avoid the generation of a short life cycle of an object or variable.
In these circumstances, the definition of an object from the buffer pool. That the management of an object than the cost of pool formation and recovery of the frequent targets of many of the expenses small.
(5) only in the role of the scope of the object to initialize.
JAVA permit any place in the code definitions and initialize the object. This role can be only in the framework of the object to initialize. System in order to save costs.
Example:
SomeObject so = new SomeObject ();
If (x == 1) then
(
Foo = so.getXX ();
)
Can be amended to read:
if (x == 1) then
(
SomeObject so = new SomeObject ();
Foo = so.getXX ();
)
2. Abnormal (Exceptions)
JAVA language provides a try / catch to capture user-friendly hair abnormalities, treatment for abnormalities. However, if used improperly, the procedure will also give the performance of JAVA impact. Therefore, in order to pay attention to the following two points.
(1) to avoid the application of logic to use try / catch
If you can use if, while statements, etc. to deal with logic, it's not as far as possible, try / catch statement
(2) reuse abnormal
Must be carried out in the treatment of abnormal, we should reuse as much as possible abnormal objects that already exist. At that deal with the abnormal, the generation of an exception object to be consumed most of the time.
3. Threaded (Threading)
A high-performance applications will normally be used in threads. Since the thread to make full use of system resources. Wait for the other thread because the hard disk or network to read and write from time to time, procedures and operations will continue to deal with. However, the use of inappropriate threads will also affect the performance of the procedure.
Example 2: The proper use of type Vector
Vector is mainly used to preserve various types of objects (including the same type and different types of objects). However, in some cases the procedures used will impact on performance. This is mainly from the Vector class determined by the characteristics of both. First, Vector provides a thread-safety protection. Even if the Vector Class in many ways simultaneously. However, if you have confirmed you are single-threaded applications, the synchronization of these methods is entirely unnecessary. Second, the storage at the various search Vector object, usually spend a lot of time to kind of match. When these objects are the same type, they match completely unnecessary. Therefore, it is necessary to design a single-threaded, and preservation of specific types of object or collection type instead of Vector. To replace the procedures are as follows (StringVector.java):
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 (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 <count; i + +)
(
/ / Check for a match
if (data [i]. equals (str))
(
System.arraycopy (data, i +1, data, i, count-1); / / copy data
/ / Allow previously valid array element be gc'd
data [- count] = null;
return;
)
)
)
public final String getStringAt (int index) (
if (index <0) (return null;)
else if (index> count)
(
return null; / / index is> # strings
)
else (return data [index]; / / index is good)
)
/ * * * * * * * * * * * * * * * * StringVector.java * * * * * * * * * * * * * * * * * /
Therefore, the code:
Vector Strings = new Vector ();
Strings.add ( "One");
Strings.add ( "Two");
String Second = (String) Strings.elementAt (1);
Can be used to replace the code as follows:
StringVector Strings = new StringVector ();
Strings.add ( "One");
Strings.add ( "Two");
String Second = Strings.getStringAt (1);
This thread can be optimized to improve the performance of JAVA program. Procedures for testing are as follows (TestCollection.java):
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 [vector | stringvector]");
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 ((finish-start));
start = 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 (assuming the standard time for one, the smaller the better performance):
Thread about the operation of some aspects of attention should be paid as follows.
(1) to prevent too many simultaneous
As indicated above, usually unnecessary synchronization will cause a decline in performance. Therefore, if the process is single-threaded, you must not use synchronization.
(2) synchronization method and not to sync the entire code segment
Of a synchronized method or function than the entire code segment better synchronization performance.
(3) for each object the use of many "lock" mechanism to increase concurrency.
Each object in general there is only one "lock", which shows that if the two thread implementation of an object of two different methods of synchronization, it will happen, "Deadlock." Even if these two methods do not share any resources. To avoid this problem, the implementation of an object can be "multi-lock" mechanism. 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)
Including a lot of input and output, but most are involved in the hard disk, network or database operations read and write. For read and write operation, is divided into cache and there is no cache; for the operation of the database, but also has many types of JDBC driver can select. But no matter what, it will give an impact on the performance of the procedure. Therefore, the necessary attention to the following:
(1) the use of input and output buffer
As far as possible the use of many of the cache. However, if want to always refresh the cache (flush), is recommended not to use the cache.
(2) output stream (Output Stream) and Unicode strings
At that time, Output Stream and Unicode string, Write more types of expenses. Because it wants to achieve Unicode byte (byte) the conversion. Therefore, if possible, in the use of Write-type conversion before the implementation or use Writer instead of OutputStream class type to use.
(3) When the use of serialization to be transient
When the sequence of a class or object, for those types of atoms (atomic) or the reconstruction of the elements to form the type of knowledge for the transient. This would not have carried out every serialization. If the sequence of the target of transmission on the network, this small change will be greatly improved performance.
(4) the use of cache (Cache)
For those who want to use and do not always change the object or data, you can put it is stored in the cache. This will improve the speed of access. This is the return from the database result set is particularly important.
(5) the use of fast JDBC driver (Driver)
JAVA to access the database provided the four methods. This is one of two JDBC drivers. JAVA outsourcing is a local drive; the other is the complete JAVA drive. Specific to the use of which was deployed in accordance with JAVA application environment and set itself.
5. A number of other experiences and skills
(1) the use of local variables
(2) to avoid in the same class had a function or method calls (get or set) to set up or call the variable.
(3) to avoid generating the same cycle at a variable or a function call (the same variable parameters)
(4) as far as possible the use of static, final, private, such as keyword
(5) When you copy a large amount of data, use System.arraycopy () command.
Related Posts of Performance Optimization of Java
-
Referred to the development of Microsoft's Janus skelter
Chapter 1 of this book for basic knowledge about the basic concepts of SharePoint, the basic object model, coding notes, and on a set to develop and deploy packaged together to create the project structure; Chapter 2 for the Web Parts development, in ...
-
Student candidates for software recommendations
Financial crisis has come, the project got worse, employees are brothers, should not because there is no project, on vacation or dismissal. However, small businesses, how many did not make money, can only help each other to tide over the difficulties ...
-
Optimize Debian / Ubuntu under ruby
We all know that Debian / Ubuntu through apt-get to install the ruby packages very slow (Reference: Ruby implementation of various amendments to the Performance Evaluation version) Usually we are, through their own www.ruby-lang.org from the download ...
-
Rails to monitor the process of memory leaks skills
Rails applications easier to encounter two types of performance problems: Rails implementation of a class are very slow, CPU consumption too high; The other is the process of memory leaks Rails. To resolve these two types of questions are necessary b ...
-
Rails January of dynamic
More than a month before, Rails 2.2.2 released at the same time, the official immediately issued a statement, saying that Rails 2.3 is under development. See the news, while lamenting on the Rails Core Team, the progress is so compact, at the same ti ...
-
ruby MBARI large patches Performance Evaluation Report
Before JavaEye news ruby memory leak culprit - the specter of a detailed analysis of the current pointer Ruby official version (MRI version) causes memory leaks. Brent Roman today issued a Super patch , Which contains 6 patch file to resolve the Ruby ...
-
Pring Beanfactory at the jsp, servlet, web.xml and other configuration
Keywords: spring beanfactory Spring in the web application called the Beanfactory 1) Configure web.xml Java code <? xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE web-app PUBLIC "- / / Sun Microsystems, Inc. / / ...
-
hibernate study of the second
Persistence of three main points: 1, a statement for persistent fields accessors (accessors) and whether the variable signs (mutators) Property statement is not necessarily required for the public's. Hibernate can be default, protected or private ...
-
Hibernate II Study Notes
11. Many-to-many Of many that can be converted to two one-to-many many-to-many data only from one end of the maintenance, if at both ends of maintenance, will be reported to the conflict between form the primary key of the error message. Many-to-many quer
-
log4j easy application in java
JAVA development, frequently used the log output, in a so-called most of the software company will have its own set of configuration style, re-read the configuration file to initialize property of the log, it will be good, but sometimes may not need ...













Leave a Reply