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. However, for example
If an object implements the cloneable interface, we can call its clone () method. The clone () method is not called.
Use any class to construct a function.
When using design pattern, If you create an object in factory mode, use
The clone () method is very easy to create a new object instance. 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 a large number of lines to create
(In good cases, a buffer pool is used ). This technology can support concurrency in many
I/O Stream applications, such as web servers, quotations, and auction applications. However, creating a Java thread requires
Considerable overhead.
JDK 1.4 introduces a non-blocking I/O Library (Java. NiO ). If the application requires an earlier JDK version
Here is a software package that supports non-blocking I/O.
1.3 usage exceptions with caution
Exceptions are detrimental to performance. To throw an exception, you must first create a new object. Throwable interface Constructor
Use the local (native) method named fillinstacktrace () to check the heap
Stack to collect call tracing information. As long as an exception is thrown, the VM must adjust the call stack.
Creates a new object.
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
Set to null, INTEGER (byte, short, Int, long) to 0, float, and double
Set it to 0.0, and set the logical value to false. When a class is derived from another class, pay special attention to this 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 Java core APIs,
For example, 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
Opportunity inline (Inline) All final methods (this is related to the specific compiler implementation ). This will enable performance
An average increase of 50%.
1.6 use local variables whenever possible
Parameters passed during method call and temporary variables created in the call are stored in the stack.
Fast. Other variables, such as static variables and instance variables, are created in heap, which is slow. Another
In addition, depending on the specific compiler/JVM, local variables may be further optimized.
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, but instead shifts the value three places to the left.
Multiply by 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
Make the code more difficult to understand, so it is best to add some comments.
Ii. jsp, EJB, and JDBC
The performance improvement techniques described earlier are suitable for most Java applications. The questions to be discussed later are suitable for use.
JSP, EJB, or JDBC applications.
1. Use the buffer tag
Some application servers have added the JSP-oriented buffer tag function. For example, the WebLogic Server of Bea is from version 6.0
This feature is supported at the beginning, and the open symphony project also supports this feature. JSP buffer tag can be slowed down
The whole page can be buffered. When the JSP page is executed, if the target segment is already in the buffer,
The code that generates the snippet does not 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
The page-level buffer can save the page execution results for subsequent requests.
For pages with complex code logic, it is obvious to improve the performance by using the buffer tag; otherwise, the effect may be slightly
Poor.
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, every get method is one
Remote calls. The Session Bean accessing the object bean is local and can organize all the data into a structure. However
And return its value.
Accessing the Entity Bean through Session Bean encapsulation can improve transaction management, because Session Bean is only at the transaction side.
This API is submitted only when it is created. Each direct call to the get method generates a transaction, and the container will
After the transaction, perform the "load-read" operation. 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, change it to use JDBC to access data within the session bean.
Database to achieve better performance.
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
Merge 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 the output results
More flexible. However, only when the referenced content changes frequently or the request to the home page does not appear
Previously, when the referenced page cannot be determined, it is cost-effective to use the include action.
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 has a package
Setting the read-only attribute is helpful for improving the performance, because the container no longer needs to perform storage operations.
.
5. Buffer access to the EJB home
The EJB home interface is obtained through the JNDI name search. This operation requires considerable overhead. It is best to search for JNDI
In the init () method of servlet. It is recommended to create
Ejbhomecache class. The ejbhomecache class is generally implemented as Singleton.
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:
.
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 involves the stub program that creates an IIOP request and transmits the request over the network. It is also
RMI call. To implement the local interface, we must make the following changes:
The method cannot throw a java. RMI. RemoteException, including an exception derived from RemoteException,
For example, transactionrequiredexception, transactionrolledbackexception, and
Nosuchobjectexception. EJB provides equivalent local exceptions, such
Transactionrequiredlocalexception, transactionrolledbacklocalexception, and
Nosuchobjectlocalexception.
All data and return values are passed through reference instead of values. The Local interface must be deployed 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 the bean
If a local interface is provided, its reference cannot be serialized.
7. Generate the primary key
There are many ways to generate a primary key in EJB. The following describes several common methods and their features. Use Data
Database built-in identity mechanism (SQL Server identity or Oracle sequence ). The disadvantage of this method is that
Poor EJB portability. The Entity Bean automatically calculates the primary key value (for example, incremental operations ). Its disadvantage is that it requires transactions
Serializable and slow.
Use NTP and other clock services. This requires local code for a specific platform to fix the bean to a specific
. In addition, it also leads to the possibility that, on a multi-CPU server, the same millisecond is generated
Into two primary keys. Use Microsoft's idea to create a guid in bean. However, if you do not seek help
JNI and Java cannot determine the MAC address of the NIC. If JNI is used, the program depends on a specific OS.
There are several other methods, but these methods also have their own limitations. It seems that there is only one ideal answer:
Use RMI and JNDI together. Bind the remote RMI object to the JNDI tree through RMI registration. The client program is implemented through JNDI
Search. The following is an example:
Public class keygenerator
Extends unicastremoteobject implements
Remote {Private Static long keyValue = system. currenttimemillis ();
Public static synchronized long getkey ()
Throws RemoteException {return keyValue ++ ;}
8. Clear unnecessary sessions in time
To clear sessions that are no longer active, many application servers have the default session timeout time, usually 30 minutes.
When the application server needs to save more sessions, if the memory capacity is insufficient, the operating system will convert some memory data
When moving to a disk, the application server may also use the most recently used algorithm
Some inactive sessions are dumped to the disk, and may even throw an "out of memory" exception. In a large-scale system
The cost of a row-based session is very expensive. When the session is no longer needed, it should be called in time
The httpsession. invalidate () method clears the session. The httpsession. invalidate () method can usually be
Call the exit page of the application.
9. Disable useless sessions on the JSP page
For pages that do not need to track session Status, disabling automatically created sessions can save some resources. Use the following
Page command:
<% @ Page session = "false" %>
10. servlet and memory usage
Many developers store a large amount of information in user sessions at will. In some cases, the object stored in the session does not
There is a mechanism for timely collection of garbage. In terms of performance, the typical symptom is that the user feels the system changes periodically.
Slow, but it cannot be attributed to any specific component. If you monitor the JVM heap space, the memory is used.
Usage is not normal. There are two main ways to solve such memory problems. The first method is
Implement the httpsessionbindinglistener interface in the bean with a range of sessions. In this way, as long as
The valueunbound () method can explicitly release the resources used by the bean.
Another method is to invalidate the session as soon as possible. Most application servers have a session expiration Interval
. In addition, you can call the setmaxinactiveinterval () method of the session programmatically.
This parameter is used to set the maximum interval of customer requests allowed by the servlet container before the session is voided, in seconds.
11. Http keep-alive
The keep-alive function keeps the client-to-server connection valid. When a subsequent request to the server appears,
The keep-alive function avoids or reestablishes a connection. Most Web servers on the market, including
IPlanet, IIS, and Apache Support HTTP keep-alive. For websites that provide static content, this
Functions are usually useful. However, for websites with heavy load, there is another problem:
The user retains the opened connection, but it also affects the performance, because during the pause process
The resources to be released are still occupied. When the Web server and Application Server run on the same machine, keep-
The impact of the alive function on resource utilization is particularly prominent.
12. JDBC and Unicode
You must have understood some measures to improve the performance when using JDBC, such as using the connection pool and choosing the Correct storage
And the SQL statements that are directly executed, the redundant columns are deleted from the result set, and the SQL statements are compiled in advance. In addition
In addition to the easy-to-see choice, another good choice for improving performance may be to save all the character data as Unicode
(Code page 13488 ). Java processes all data in unicode format, so the database driver does not have to execute
Line conversion process. But remember: if this method is used, the database will become larger, because every Unicode word
It requires 2 bytes of storage space. In addition, if other non-Unicode programs access the database, the performance problem persists.
The old one will appear, because the database driver still has to execute the conversion process.
13. JDBC and I/O
If an application needs to access a large dataset, consider using block extraction. Default
JDBC extracts 32 rows of data each time. For example, if we want to traverse a 5000-row record set, JDBC is required.
You must call the database 157 times to extract all the data. If the block size is changed to 512, the number of times the database is called
It will be reduced to 10 times. In some cases, this technology is ineffective. For example
If for update is specified in the query, the block operation method is no longer valid.
14. Memory Database
Many applications need to store a considerable amount of data in session objects in units of users. Typical applications such as shopping baskets and
Directory. Because this type of data can be organized in the form of rows/columns, many applications create a large Vector
Or hashmap. Saving this type of data in a session greatly limits the scalability of the application, because
Memory must at least reach the memory used by each session multiplied by the maximum number of concurrent users, which not only makes the server price
Expensive, and the interval between garbage collection may be extended to an intolerable level.
Some people transfer the shopping basket/directory function to the database layer, which improves scalability to a certain extent. However
Some features also have problems at the database layer, and the root cause of the problem is the architecture of most relational database systems.
. For relational databases, one of the important runtime principles is to ensure the stability and availability of all write operations.
Therefore, all performance problems are related to the ability to physically write data to a disk. Relational Database attempts to decrease
I/O operations, especially for read operations, but the main way to achieve this is to execute a set of buffer mechanisms.
Complex algorithms, and this is the main reason why the performance bottleneck at the first database layer is always CPU.
A solution to replace traditional relational databases is to use a database running in the memory (in-memory
Database), such as TimesTen. The starting point of the memory database is to allow temporary data writing, but the data
You do not have to save it to the disk permanently. All operations are performed in the memory. In this way, the memory database does not need to be complex.
And can adopt a relatively simple locking mechanism, so the speed is very fast.
3. Graphic Interface Application
The content described in this article is suitable for applications (Applet and common applications) on the graphic user interface.
Swing. 1. Use jar to compress class files
Java file (JAR file) is a file compressed according to the JavaBean standard. It is the main tool for publishing the JavaBean Component.
Method and recommendation method. Jar files help reduce the file volume and shorten the download time. For example, it helps the Applet
Increase the startup speed. A jar file can contain one or more related beans and support files.
Form, sound, HTML, and other resources. To specify the JAR file in the HTML/JSP file, you only need to add
Input the archive = "name. Jar" statement.
2. prompt the applet Loading Process
Have you ever seen a website that uses an applet and noticed that there is a placeholder in the place where the applet should be run?
What happens when the applet is downloaded for a long time? The biggest possibility is that the user turns around and leaves. In this
In this case, displaying the information of an applet being downloaded will undoubtedly help encourage users to continue waiting. Let's take a look.
Let's look at a specific implementation method. First, create a small applet, which is responsible for downloading the official
Applet:
Import java. Applet. Applet;
Import java. Applet. appletstub;
Import java. AWT. label;
Import java. AWT. graphics;
Import java. AWT. gridlayout;
Public class preloader extends applet implements runnable, appletstub {
String largeappletname;
Label label;
Public void Init (){
// The formal applet to be loaded
Largeappletname = getparameter ("applet"); // "Please wait" prompt
Label = new label ("Please wait..." + largeappletname );
Add (Label );
}
Public void run (){
Try
{
// Obtain the class of the applet to be loaded
Class largeappletclass = Class. forname (largeappletname );
// Create the instance for which the applet is to be loaded
Applet largeapplet = (applet) largeappletclass. newinstance ();
// Set the stub program of the Applet
Largeapplet. setstub (this );
// Cancel the "Please wait" Message
Remove (Label );
// Set the Layout
Setlayout (New gridlayout (1, 0 ));
Add (largeapplet );
// Display the official Applet
Largeapplet. INIT ();
Largeapplet. Start ();
}
Catch (exception ex)
{
// Display the error message
Label. settext ("the specified applet cannot be loaded ");
}
// Refresh the screen
Validate ();
}
Public void appletresize (INT width, int height)
{
// Transfer the appletresize call from the stub program to the Applet
Resize (width, height );
}
}
The compiled code is less than 2 kb, And the download speed is fast. There are several points worth noting in the code. First, preloader implements
The appletstub interface is now available. Generally, the applet judges its codebase from the caller. In this example, we
You must call setstub () to tell the applet where to extract this information. Another thing worth noting is that,
The appletstub Interface contains many methods that are the same as the Applet Class, except for the appletresize () method. Here I
The call to the appletresize () method is passed to the resize () method.
3. Pre-mount the image before it is drawn
The imageobserver interface can be used to receive prompt information about image loading. The imageobserver interface has only one method.
Imageupdate (), which can be used to draw images on the screen with a repaint () operation. An example is provided below.
Public Boolean imageupdate (image IMG, int flags, int X, int y, int W, int H)
{
If (flags & allbits )! = 0 {
Repaint ();
}
Else if (flags & (error | abort ))! = 0 ){
Error = true;
// The file is not found. Consider displaying a placeholder
Repaint ();
}
Return (flags & (allbits | error | abort) = 0;
}
The imageupdate () method is called When graphical information is available. If further update is required, this method returns
True; if the required information is obtained, this method returns false.
4. overwrite the update Method
The default action of the update () method is to clear the screen and then call the paint () method. If you use the default Update ()
Method. Applications that frequently use images may flash. Avoid screen clearing before painting () is called.
In addition to operations, you only need to override the update () method as follows:
Public void Update (Graphics g ){
Paint (g );
}
The ideal solution is to overwrite Update () and only redraw the area on the screen that has changed, as shown below:
Public void Update (Graphics g ){
G. cliprect (X, Y, W, H );
Paint (g );
}
5. delayed re-painting
For graphic user interface applications, the main reason for poor performance can often be attributed to the low efficiency of focusing on the screen.
. This is usually observed when the user changes the window size or scrolls a window. Change
Operations such as window size or scrolling screen lead to a large number of screen re-painting events generated quickly, or even exceeds
The execution speed of related code. The best way to deal with this problem is to ignore all "late" events.
We recommend that you introduce a time difference of several milliseconds here, that is, if we receive another re-painting event immediately, we can stop it.
Processing the current event instead of processing the last re-painting event received; otherwise, we will continue to redraw the current re-painting.
.
If an event needs to start a time-consuming task, it is a good way to separate a working thread; otherwise,
Some parts may be frozen because only one event can be handled at a time. The following provides a simplified event processing method.
Single example, but after extension, it can be used to control the working thread.
Public static void runonce (string ID, final long milliseconds ){
Synchronized (e_queue ){
// E_queue: a collection of all events
If (! E_queue.containskey (ID )){
E_queue.put (token, new lastone ());
}
}
Final lastone = (lastone) e_queue.get (token );
Final long time = system. currenttimemillis (); // obtain the current time
Lastone. Time = time;
(New thread () {public void run (){
If (milliseconds> 0 ){
Try {thread. Sleep (milliseconds);} // pause the thread
Catch (exception ex ){}
}
Synchronized (lastone. Running) {// wait until the last event ends
If (lastone. Time! = Time) // only process the last event
Return;
}
}). Start ();
}
Private Static hashtable e_queue = new hashtable (); Private Static class
Lastone {
Public long time = 0;
Public object running = new object ();
}
6. use dual-Buffer
The entire image is displayed immediately after the drawing is completed in the buffer area outside the screen. Because there are two buffers
The program can switch back and forth. In this way, we can use a low-priority thread to take charge of drawing, so that the program can benefit
Execute other tasks with idle CPU time. The following pseudocode snippets demonstrate this technology.
Graphics mygraphics;
Image myoffscreenimage = createimage (SIZE (). Width, size (). Height );
Graphics offscreengraphics = myoffscreenimage. getgraphics ();
Offscreengraphics. drawimage (IMG, 50, 50, this );
Mygraphics. drawimage (myoffscreenimage, 0, 0, this );
7. Use bufferedimage
Java JDK 1.2 uses a soft display device to make the text look similar on different platforms. To achieve this
Java must directly process the pixels that constitute the text. Because this technology requires a large amount of bitwise replay in the memory
Early JDK has poor performance when using this technology. Java standard implementation proposed to solve this problem
A new image type, bufferedimage. The image described by the bufferedimage subclass has an accessible
Graph data buffer. A bufferedimage contains a colormodel and a set of Raster Graphic Data. This
Generally, RGB (red, green, and blue) color models are used, but gray-level images can also be processed. Its constructor is very
Simple:
Public bufferedimage (INT width, int height, int imagetype)
Imagetype allows us to specify the type of graphics to buffer, such as 5-bit RGB, 8-bit RGB, and grayscale
.
8. Use volatileimage
Many hardware platforms and their operating systems provide basic hardware acceleration support. For example, hardware acceleration generally provides
The rectangle filling function is more efficient than using the CPU to complete the same task. Due to hardware acceleration isolation
Allows multiple workflows to run concurrently. This reduces the pressure on CPU and system bus
It can run faster. Volatileimage allows you to create a hardware-accelerated image and manage its content.
Because it directly utilizes the capabilities of the lower-layer platform, the performance improvement mainly depends on the graphic adapter used by the system.
Volatileimage content may be lost at any time, that is, it is "unstable )". Therefore
Before using a graph, check whether its content is lost. Volatileimage can check whether the content is
Method of loss:
Public abstract int validate (graphicsconfiguration GC); public abstract
Boolean contentslost ();
Each time the content is copied from the volatileimage object or written to the volatileimage object, the validate () method should be called.
Method. The contentslost () method tells us that since the last validate () call, the image content is
No. Although volatileimage is an abstract class, do not derive a subclass from it. Volatileimage
You should use component. createvolatileimage () or
Graphicsconfiguration. createcompatiblevolatileimage () method.
9. Use Window blitting
During the scrolling operation, all visible content must be repainted, resulting in a large amount of unnecessary re-painting. Xu
The graphic subsystems of multiple operating systems, including Win32 GDI, MacOS, and X/windows, all support windows
Blitting technology. Window blitting technology directly moves the image to a new position in the screen buffer, only re-painting
New region. To use the window blitting Technology in swing applications, the configuration method is as follows:
Setscrollmode (INT mode );
In most applications, this technology can improve the rolling speed. Only in one situation, window
Blitting reduces performance, that is, the application performs rolling operations in the background. If the user is rolling an application,
Then it is always on the frontend without worrying about any negative impact.