TIPS: Java performance optimization tips

Source: Internet
Author: User

I. General

The general topic is suitable for most Java applications.

  1.1 create a class instance without the new Keyword

When you create an instance with the new Keyword, all constructors in the constructor chain are automatically called. But if an object implements the Cloneable interface, we can call its clone () method. The clone () method does not call any class constructor.

When using Design Pattern, it is very easy to use the clone () method to create a new object instance if you create an object in Factory mode. For example, the following is a typical Implementation of the Factory mode:

Public static Credit getNewCredit (){
Return new Credit ();
}

The improved code uses the clone () method as follows:

Private static Credit BaseCredit = new Credit ();
Public static Credit getNewCredit (){
Return (Credit) BaseCredit. clone ();
}

The above idea is also useful for Array Processing.

  1.2 use non-blocking I/O

Earlier JDK versions do not support non-blocking I/O APIs. To avoid I/O congestion, some applications use the method of creating a large number of threads (in good cases, a buffer pool is used ). This technology can be seen in many applications that must support concurrent I/O streams, such as Web servers, quote and auction applications. However, creating a Java thread requires considerable overhead.

JDK 1.4 introduces a non-blocking I/O Library (java. nio ). If an application requires JDK of an earlier version, there is a software package that supports non-blocking I/O.

See adjust Java I/O performance on Sun China website.

  1.3 usage exceptions with caution

Exceptions are detrimental to performance. To throw an exception, you must first create a new object. The constructor of the Throwable interface calls the local (Native) method named fillInStackTrace (), the fillInStackTrace () method checks the stack, and collects Call trace information. As long as an exception is thrown, the VM must adjust the call stack because a new object is created during processing.

Exceptions can only be used for error handling and should not be used to control program processes.

  1.4 do not reinitialize the variable

By default, Java initializes the variable to a definite value when calling the class constructor: all objects are set to null, and integer variables (byte, short, int, long) set it to 0, float and double variables to 0.0, and logical value to false. This is especially important when a class is derived from another class, because when an object is created using the new keyword, all constructors in the constructor chain are automatically called.

  1.5 specify the final modifier of the class as much as possible

Classes with final modifiers cannot be derived. There are many examples of final applications in the Java core API, such as java. lang. String. Specifying final for the String class prevents people from overwriting the length () method.

In addition, if you specify a class as final, all the methods of this class are final. The Java compiler will look for opportunities to inline (inline) All final methods (this is related to the specific compiler implementation ). This can increase the performance by an average of 50%.

  1.6 use local variables whenever possible

The parameters passed during method calling and the temporary variables created in the call are saved in the Stack, which is faster. Other variables, such as static variables and instance variables, are created in Heap, which is slow. In addition, local variables may be further optimized depending on the specific compiler/JVM. See use stack variables whenever possible.

  1.7 multiplication and division

Consider the following code:

For (val = 0; val <100000; val + = 5) {alterX = val * 8; myResult = val * 2 ;}

Replacing multiplication with shift operations can greatly improve performance. The modified code is as follows:

For (val = 0; val <100000; val + = 5) {alterX = val <3; myResult = val <1 ;}

The modified code does not multiply by 8. Instead, it uses the equivalent three-bit left shift operation, and one-bit left shift operation is equivalent to multiplying 2. Correspondingly, the one-bit operation on the right is equivalent to dividing by 2. It is worth mentioning that, although the shift operation is fast, it may make the code more difficult to understand, so it is best to add some comments.

Ii. J2EE

The performance improvement techniques described earlier are suitable for most Java applications. The questions to be discussed later are suitable for JSP, EJB, or JDBC applications.

  2.1 use a buffer flag

Some application servers have added the JSP-oriented buffer tag function. For example, the WebLogic Server of BEA supports this function from version 6.0, and the Open Symphony project also supports this function. The JSP buffer tag can buffer both page fragments and the whole page. When the JSP page is executed, if the target segment is already in the buffer, the code that generates the segment will no longer need to be executed. Page-level buffer captures requests to a specified URL and caches the entire result page. This feature is extremely useful for shopping baskets, directories, and portals. For such applications, page-level buffering can save the results of page execution for subsequent requests.

For pages with complex code logic, the performance improvement by using the buffer tag is obvious; otherwise, the performance may be slightly inferior.

See improving the performance and stability of JSP applications with buffer technology.

  2.2 always access the Entity Bean through the session Bean

Direct access to the Entity Bean is not conducive to performance. When the client program remotely accesses the object Bean, each get method is a remote call. The Session Bean accessing the object Bean is local. It organizes all the data into a structure and returns its value.

The access to the Entity Bean encapsulated by the session Bean can improve the transaction management, because the Session Bean will be submitted only when it reaches the transaction boundary. Each direct call to the get method generates a transaction, and the container will execute a "load-read" operation after each Entity Bean transaction.

In some cases, using the Entity Bean will lead to poor program performance. If the only purpose of the entity Bean is to extract and update data, you can use JDBC to access the database within the session Bean to achieve better performance.

  2.3 select an appropriate reference mechanism

In a typical JSP application system, the page header and footer are often extracted, and the page header and footer are introduced as needed. Currently, there are two main methods to introduce external resources in JSP pages: include commands and include actions.

Include command: for example, <% @ include file = "copyright.html" %>. This command introduces specified resources during compilation. Before compilation, the page with the include command and the specified resource are merged into a file. The referenced external resources are determined at compilation, which is more efficient than the resources determined at runtime.
Include action: for example, <jsp: include page = "copyright. jsp"/>. This action introduces the result generated after the specified page is executed. Because it is completed at runtime, the control of output results is more flexible. However, the include action is cost-effective only when the referenced content changes frequently or the referenced page cannot be determined before the request to the home page appears.

  2.4 set the read-only attribute in the deployment descriptor

The deployment descriptor of the Entity Bean allows you to set all get methods to "read-only ". When a transaction unit only includes read operations, setting the read-only attribute improves performance because the container does not have to perform storage operations.

  2.5 Buffer access to EJB Home

The EJB Home interface is obtained through the JNDI name search. This operation requires considerable overhead. It is best to put the JNDI search in the init () method of Servlet. If multiple applications frequently encounter EJB access, it is best to create an EJBHomeCache class. The EJBHomeCache class is generally implemented as singleton.

  2.6 implement Local interface for EJB

The Local interface is newly added to the EJB 2.0 specification, which allows the Bean to avoid the overhead of remote calls. Consider the following code.

PayBeanHome home = (PayBeanHome)
Javax. rmi. PortableRemoteObject. narrow
(Ctx. lookup ("PayBeanHome"), PayBeanHome. class );
PayBean bean = (PayBean)
Javax. rmi. PortableRemoteObject. narrow
(Home. create (), PayBean. class );

The first statement indicates that we are looking for the Home interface of Bean. This query is performed through JNDI, which is an RMI call. Then, we locate the remote object and return the proxy reference, which is also an RMI call. The second statement demonstrates how to create an instance. It involves the stub program that creates an IIOP request and transmits the request over the network. It is also an RMI call.

To implement the local interface, we must make the following changes:

The method cannot throw a java. rmi. RemoteException, including exceptions derived from RemoteException, such as TransactionRequiredException, TransactionRolledBackException, and NoSuchObjectException. EJB provides equivalent local exceptions, such as TransactionRequiredLocalException, TransactionRolledBackLocalException, and NoSuchObjectLocalException.

All data and return values are passed through reference instead of values.
The Local interface must be used on the machine where the EJB is deployed. In short, the customer program and the components that provide services must run on the same JVM.
If Bean implements a local interface, its reference cannot be serialized.
For more information, see use local references to improve EJB access efficiency.


2.7 generate a primary key

There are many ways to generate a primary key in EJB. The following describes several common methods and their features.

Use the database's built-in IDENTITY mechanism (SQL Server's IDENTITY or Oracle's SEQUENCE ). The disadvantage of this method is that EJB has poor portability.

The Entity Bean automatically calculates the primary key value (for example, incremental operations ). Its disadvantage is that transactions must be serializable and slow.

Use NTP and other clock services

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.