Fast "in the details of the Java Program Performance optimization techniques

Source: Internet
Author: User
Tags error handling exception handling final finally block garbage collection sql variables stmt
J2ee| Program | skill | performance | Optimization Application The performance of the system developed by the Java platform is a problem that the users and developers of the system are concerned about, this paper discusses the effect of code on performance from the aspects of server programming, and summarizes some suggestions to solve.

Key words: Performance, JAVA,J2EE,EJB,SERVLET,JDBC

   I. Overview

Java 2 Platform, Enterprise Edition is the development platform used by many commercial application systems, which provides a component-based approach to designing, developing, assembling, and deploying enterprise-class applications. The Java EE platform provides a multi-tiered, distributed application model that enables faster development and release of new application solutions.
Java EE is a technical specification that defines the application development architecture and a deployment environment for the entire standard, as long as the application developer is focused on the implementation of specific business logic and business rules, while other system development issues such as transaction, persistence, security, etc. can be handled by the application container or server. Once development is complete, it can be easily deployed to the application server where the specification is implemented.

As a commercial application system on the Web, the number of people visiting the network is numerous, in the case of extensive access, there will be contradictions between excessive resource requests and limited server resources (memory, CPU time, network bandwidth, etc.), and the performance of the application system is very important, sometimes the correct code does not guarantee the success of the project, Performance is often the final key to determining whether a project is successful or not.

In this paper, we discuss the optimization and improvement of code performance in Java server-side from the aspect of performance.

   second, common Java programming

The Java-EE Language Foundation is a common Java code problem in the application system performance impact, the following discussed some aspects should be noted.

• Use StringBuffer instead of string

When dealing with the addition of strings, the common writing is: ...

String str1 = "Hello";
String str2 = "Welcome to the World";
String STR3 = str1 + "," + str2 + "!";
System.out.println (STR3);
As many people know, such code efficiency is very low, because string is used to store strings constants, if you want to perform "+" operations, the system will generate some temporary objects, and the management of these objects, resulting in unnecessary overhead.

If the string has a connected operation, the alternative is to use the Append method of the StringBuffer class, and its default constructor and append implementations are:

Public StringBuffer () {//constructors
This (16); Default Capacity 16}

Public synchronized StringBuffer append (String str) {
if (str = null) {
str = string.valueof (str);
}

int Len =str.length ();
int Newcount = count + len;
if (Newcount > Value.length)

Expandcapacity (Newcount);

Expansion capacity
Str.getchars (0, Len, value, count);
Count = Newcount;
return this;
}
When the size of the string exceeds the default 16 o'clock, the code expands the capacity to avoid the expansion of the object's capacity, a better way to:

StringBuffer buffer = new StringBuffer (30);
Allocates the specified size.
Buffer.append ("Hello");
Buffer.append (",");
Buffer.append ("Welcometo world!");
String str = buffer.tostring ();
• Allocate reasonable space and size when generating objects

Many of the classes in Java have its default space allocation size, and for the initialization of some size objects, the size of the object should be expected, and then initialized, as the example above illustrates the problem, and when StringBuffer was created, we specified its size.

Another example is the vector, when the vector vect=new vector () is declared, the system calls:

Public Vector () {//default constructor
This (10); The capacity is 10;
}
The default allocation is 10 object size capacity. When you execute the Add method, you can see that the specific implementation is:..

Public synchronized Boolean add (Object o) {
modcount++;
Ensurecapacityhelper (elementcount+1);
elementdata[elementcount++] =o;

return true;
}

private void Ensurecapacityhelper (int mincapacity) {
int oldcapacity = Elementdata.length;
if (Mincapacity > Oldcapacity) {
Object olddata[] = elementdata;
int newcapacity = (capacityincrement > 0)? (Oldcapacity + capacityincrement):
(oldcapacity * 2);
if (Newcapacity < mincapacity) {
newcapacity = mincapacity;
}
Elementdata = new Object[newcapacity];
System.arraycopy (olddata, 0, elementdata, 0, Elementcount);
}
}
We can see that when the vector is larger than the original size, some of the code is designed to expand capacity, in the knowledge of the vector size in advance, you can specify its size, to avoid the cost of capacity expansion, such as the vector size of 100, when the initialization can be like this.

Vector Vect =. New Vector (100);
• Optimized circulation body

Cycle is a more repetitive operation of the place, if the number of cycles, the circulation of bad code on the efficiency of the impact will be magnified and become prominent. Consider the following code slice:..

Vector vect = new vector (1000);
...
for (inti=0; I<vect.size (); i++) {
...
}
The For Loop section is rewritten as:

int size = Vect.size ();
for (int i=0; i>size; i++) {
...
}
If you size=1000, you can reduce the system call cost of size () 1000 times, avoiding repeated calls to the loop body.

Look at the following code:.

for (int i = 0;i <100000;i++)
if (i%10 = = 9) {
..//Every 10 times
}
Rewriting can also improve efficiency:.

For (inti =0,j =10 i<100000; i++,j--) {
if (j = = 0) {
..//Every 10 times
j = 10;
}
}
Therefore, when there is a larger cycle, we should check whether there is a low efficiency in the cycle, looking for better solutions to improve.

• Creation of objects

Use new to initialize an instance of a class as little as possible, when an object is initialized with new, all constructors of its constructor chain are called, so the new operator consumes the system resources, and the new object takes more time than the local variable assignment. Also, when objects are generated, the system takes time for garbage collection and processing.

When new creates an object that is unavoidable, be careful to avoid using new to initialize an object multiple times.

Try to create the object when you use it. Such as:

NewObject object = new NewObject ();
int value;
if (i>0)
{
Value =object.getvalue ();
}
Can be modified to:

int value;
if (i>0)
{
NewObject object = new NewObject ();
Value =object.getvalue ();
}
In addition, you should try to reuse an object instead of declaring a new homogeneous object. One way to reuse an object is to change the value of the object, such as by changing the object's variables in such a way as setvalue to achieve reuse.

• Considerations for variables

Use local variables as much as possible, and the parameters passed when the method is invoked and the temporary variables created in the call are saved in the stack (stack) faster. Other variables, such as static variables, instance variables, and so on, are created in the heap (Heap) in a slower speed.

Try to use a static variable, the modifier static, if the variable in the class does not change with his instance, it can be defined as a static variable, so that all of his instances share the variable.

• Method Calls

In Java, everything is an object, and if a method is invoked, the processor first checks to see which object the method belongs to, whether the object is valid, what type of object it belongs to, and then select the appropriate method and invoke it.

You can reduce the invocation of a method by the same method:

public void Callmethod (int i) {
if (i ==0) {
Return
}
..//Other handling
}
If called directly,

int i = 0;
...
Callmethod (i);
It would be better to write:

int i = 0;
...

if (i ==0) {
Callmethod (i);
}
Without affecting the readability and so on, several small methods can be synthesized into a large method.

In addition, adding the Final,private keyword before the method is beneficial to compiler optimization.

• Careful use of exception handling

Exceptions are a Java error-handling mechanism that is useful for programs, but the exception is bad for performance. Throw an exception first to create a new object, and related processing, resulting in the overhead of the system, so the exception should be used in the case of error handling, should not be used to control program flow, the process as far as possible with while,if processing.

It is possible to synthesize a few try/catch blocks without affecting the robustness of the code.

• Sync

Synchronization is mainly in the case of multithreading, for multithreading at the same time to provide object data security mechanism, multithreading is a more complex topic, the application of multithreading is to obtain performance improvements, should minimize synchronization.

In addition, if you need to sync, you can reduce the synchronized code snippet, such as synchronizing only a method or function, not the entire code.

• Using the Java System API

Java APIs generally do the performance considerations, if the same function, the use of the API rather than write their own code, such as the common code for the group to copy:

int size = 1000;
string[] StrArray1 = new String[size];
string[] StrArray2 = new String[size];
for (inti=0;i<size;i++) {//Assignment
Strarray1[i] = (new String ("Array:" + i));
}

for (inti=0;i<size;i++) {//Copy
strarray2[i]= (New String ((String) a[i]);
}
If you use the Java-provided APIs, you can improve performance:

int size = 1000;
string[] StrArray1 = new String[size];
string[] StrArray2 = new String[size];
for (inti=0;i<size;i++) {//Assignment
Strarray1[i] = (new String ("Array:" + i));
}

System.arraycopy (strarray1,0,strarray2,0,size); Copy


The same rule is that system.arraycopy () should be used when there is a large amount of data to replicate.

   third, I/O performance

Input/output (I/O) includes many aspects, we know, the I/O operation is very cost system resources. I/O operations should be used sparingly in the program. When used, you can note:. The rational control of output function System.out.println () is useful for most of the time, especially when the system is debugged, but it also produces a lot of information appearing in the console and log, while the output has the process of serialization and synchronization, resulting in overhead.

Especially in the release, to reasonable control output, can be in the project development, design a debug tool class, in this class can realize output switch, output level, according to different conditions for different output control.

• Use caching

Read and write memory is much faster than reading and writing files, you should use buffering whenever possible.

Use a class with buffer as much as possible instead of a class without buffer, such as using BufferedReader instead of reader, and BufferedWriter instead of writer for processing I/O operations.

You can also use Bufferedinputstream instead of InputStream to get better performance.

   Four, Servlet

The servlet uses the request-response model to provide Web services, outputting and receiving user-passed parameters through Servletresponse and servletrequest, processing user requests on the server side, accessing the database on request, Access other servlet methods, invoke EJBs, and so on, and then return the processing results to the client.

• Try not to use synchronization

Servlet is multithreaded to handle different requests, based on the previous synchronization of the analysis, if there are too many synchronization will lose the advantages of multithreading.

• Don't save too much information in httpsession

Many times, it is necessary to store some objects in httpsession, can speed up the development of the system, such as the online store system will store the shopping cart information in the user's session, but when the storage of large amounts of information or large objects in the conversation is harmful, especially when the system's users a large number of visits, The need for memory can be very high.

In concrete development, there should be a trade-off between the two.

• Clear session

Typically, when a set timeout is reached and some sessions are inactive, the server releases these inactive sessions. However, in this case, especially when multi-user visit, the system memory to maintain a number of invalid sessions.

When the user exits, should manually release, recycle resources, implemented as follows: ...

HttpSession thesession = Request.getsession ();
Get current session
if (thesession!= null) {
Thesession.invalidate (); Make this session invalid
}
   v. EJB issues

EJB is the specification of Java server-side service framework, which is implemented by software vendors to implement EJB server. Application developers can focus on the business logic needed to support applications without worrying about the implementation of the surrounding framework. The EJB specification explains in detail some of the smallest but necessary services, such as transaction, security, and name.

• Cache Home Interface

The EJB library uses the Enterprise Bean's client to create its instance through its home interface. The client can access it through Jndi. The server is retrieved by the lookup method.

Jndi is a remote object that is invoked through RMI and is often more time-consuming to access. So, at design time, you can design a class that is designed to cache the home interface, get the required home interface when the system is initialized, and cache it, as long as the reference is cached.

• Encapsulating entity Beans

Direct access to entity beans is a bad habit, encapsulating access to entity beans with session beans can improve transaction management because each direct call to a GET method will result in a transaction that executes a "Load-store" after the transaction of each entity bean. Operation.

It is best to complete the encapsulation of the entity Bean in the session bean, reduce transaction processing for the container, and implement some specific business methods in the session bean.

• Free stateful session Bean

Equivalent to HttpSession, when a session bean is set to stateful, a stateful session bean, the application container (Container) may have a "passivation" (passivate) and activation (Activate) process. That is, the storage location of Sessionbean is transferred between main memory and level two cache, and there is a serialization process in this process.

Typically, the release of a stateful session bean occurs at a time-out, and the container automatically clears the object, but if it is given to the container, it may cause object passivation on the one hand, and the system will maintain a copy of the object if it is not timed out, so if we confirm the use of the Statefulsession You can explicitly release a bean after it is no longer needed, by calling:

Thesesionbean.remove ();
   Vi. Database Access

In the application system developed by Java EE, database access is generally a necessary link. The database is used to store business data for application access.

In the Java Technology Application system, the application is through the JDBC (Java Database Connectivity) implementation interface to access the database, JDBC support "Establish connection, SQL statement query, processing results" and other basic functions. When the JDBC interface is used to access the database, as long as it is implemented according to the specification, the required function can be achieved.

However, in some cases, the efficiency of the data query so that developers do not like, clearly written according to the norms of the program, the effect is very poor, resulting in the implementation of the system is not high efficiency.

• Use a fast JDBC driver

The JDBC API includes two implementation interface forms, one is a pure Java implementation of the driver, a use of ODBC driver and database client implementation, there are four driving modes and different application scope, for different application development to choose the right JDBC driver, in the same application system, If you choose a different JDBC driver, there is a difference in efficiency.

For example, if you have an enterprise application system that does not require support for different vendor databases, you can choose the JDBC driver for Mode 4, which is typically driven by a local protocol based on the database vendor, and directly invokes the protocol used by the database management system, reducing the middle tier in Mode 3.

• Use JDBC Connection pool

To improve the performance of access to the database, we can also use some of the specifications and features of JDBC 2.0, JDBC is resource-intensive, use the connection pool connection pooling when using a database connection, avoid frequent open, close connection. And we know that getting connection is more about consuming system resources.

The connection buffer pool works like this: When an application shuts down a database connection, the connection is not really released but is recycled, establishing a connection is a significant operation, and looping through the connection can significantly improve performance because of the reduction in the creation of new connections.

A code that obtains a connection through the DataSource fetch buffer pool and connects to a CUSTOMERDB data source demonstrates the following:

Context ctx = new InitialContext ();
DataSource DataSource = (DataSource) ctx.lookup ("Jdbc/customerdb");
Connection conn = datasource.getconnection ("password", "username");
• Cache DataSource

A DataSource object represents an actual data source. This data source can be a file from a relational database to a tabular form, completely dependent on how it is implemented, and once a data source object has been registered with the Jndi name service, the application can take the object from the Jndi server and use it to establish a connection to the data source.

From the example above, we know that DataSource is a way to get a connection from a connection pool, which is obtained through Jndi, and is resource-intensive.

To avoid a second Jndi call, you can cache the datasource you want to use in your system.

• Close all used resources

System is generally a concurrent system, after each application and use of resources, should be released for others to use, the meaning of each model of database resources can refer to the Sun JDBC documents, different is more valuable, the use of the completion should be guaranteed complete release.

Take a look at the following code snippet:

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
DataSource DataSource = Getdatasource ();
Take the DataSource method to achieve a slight.
conn = Datasource.getconnection ();
stmt = Conn.createstatement ();
rs = Stmt.executequery ("SELECT * from ...");
..//Other handling
Rs.close ();
Stmt.close ();
Conn.close ();
}catch (SQLException ex) {
..//Error handling
}
Rough look does not seem to have any problems, there are also close related to such as connection, such as system resources, but when an exception, the code to close the resource may not be executed, in order to ensure that the resource is actually closed, you should put the resource shutdown code to the finally block:

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
DataSource DataSource = Getdatasource ();
Take the DataSource method to achieve a slight.
conn = Datasource.getconnection ();
stmt = Conn.createstatement ();
rs = Stmt.executequery ("SELECT * from ...");

..//Other handling
}catch (SQLException ex) {
..//Error handling

}finally{
if (rs!=null) {
try {
Rs.close (); Close ResultSet}
catch (SQLException ex) {
..//Error handling
}
}

if (stmt!=null) {
try {
Stmt.close (); Close statement}
catch (SQLException ex) {
..//Error handling
}
}
if (conn!=null) {
try {
Conn.close (); Close Connection}
catch (SQLException ex) {
..//Error handling
}
}
}
• Large amount of data processing

When we read a list of things like data, reports, such as large amounts of data, you can find that the use of the EJB method is very slow, you can use direct access to the database, SQL direct access to data, thereby eliminating the EJB's recurrent costs (such as remote method calls, transaction management and data serialization, the construction of objects, etc.).

• Cache frequently used data

For a built business system, if some data is to be read frequently from the database, and the data is not constantly changing, the data can be cached in the system and read directly to the cache when used without frequent access to the database.

Cache work can read data at once when the system initializes, especially some read-only data, update the database content when the data is updated, and update the cached data values.

An example is that, in a set of enterprise application Systems, enterprise information data (such as the name of the enterprise) is used in multiple business application modules, this data can be cached, when needed, directly read the cached enterprise information data.

   Vii. Summary

Generally speaking, participate in the system operation of the code will have an impact on the performance, the actual application should form a good programming norms, the preparation of high-quality code, when system performance problems, to find the main effect of the bottleneck, and then focus on optimizing the code, can achieve a multiplier effect.

Java EE Performance Optimization includes many aspects, to achieve a good performance of the system, in addition to the code, but also in accordance with the actual operation of the system, from the server hardware and software environment, cluster technology, System architecture design, System deployment environment, data structure, algorithm design and other aspects of comprehensive consideration.

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.