Java performance optimization highlights

xiaoxiao2021-03-05  31

First, universal articles

The issue of "universal article" is suitable for most Java applications.

1.1 Examples of creating classes without NEW keywords

When you create an instance of a class with a new keyword, all constructors in the constructor chain are automatically called. But if

If an object implements a Cloneable interface, we can call its clone () method. Clone () method does not adjust

Use any class constructor.

If you use the design mode (Design Pattern), if you create an object with the Factory mode,

Clone () method is very simple 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 shown below:

Private static credit basecredit = new credit ();

Public static credit getnewcredit () {

Return (Credit) Basecredit.clone ();

The above ideas is equally useful for array processing.

1.2 use non-blocking I / O

The low version of JDK does not support Non-block I / O APIs. In order to avoid I / O blocking, some applications use a large number of lines

The approach (in good case, a buffer pool) is used. This technology can support concurrently in many

Seeing I / O streams, such as web servers, quotes, and auction applications. However, creating a Java thread requires quite

Optimistic overhead.

JDK 1.4 introduces a non-blocking I / O library (Java.nio). If the application requests the version earlier JDK,

Here is a package that supports non-blocking I / O.

1.3 cautious use

Exception is unfavorable. Throw an exception first to create a new object. Throwable interface constructor

Use a native method called FillInstackTrace (), FillInstackTrace () method checks heap

Stack, collect the trace information. As long as there is an abnormality, the VM must adjust the calling stack because of the process of processing

A new object is created in it.

An exception can only be used for error processing, and should not be used to control the program process.

1.4 Do not repeat initialization variables

By default, when the class constructor is called, Java initializes the variable into a determined value: all objects

Set to null, integer variables (byte, short, int, long) set to 0, Float and Double Variables

Set 0.0, the logical value is set to false. This should pay particular attention when a class is derived from another class.

When creating an object with a new keyword, all constructor in the constructor chain are automatically called.

1.5 Try to specify the Final modifier class

Classes with Final modifiers are not born. In the Java core API, there are many examples of Final,

For example, java.lang.string. Specifying Final for String class to prevent people from overwriting the Length () method.

Also, if you specify a class for Final, all methods of this class are Final. Java compiler will look for

Opportunities inline all Final methods (this is related to specific compiler implementation). This can make performance

Average increases by 50%.

1.6 Try to use local variables

The parameters passed when calling the method and the temporary variables created in the call are saved in the stack (STACK), speed

Faster. Other variables such as static variables, example variables, etc. are created in the heap, slower speed. In addition, dependent on specific compiler / JVM, local variables may also 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;}

The replacement of multiplication operation can greatly improve performance. Below is the modified code:

FOR (VAL = 0; Val <100000; VAL = 5)

{Alterx = val << 3; myresult = val << 1;}

The modified code is no longer multiplied by 8 operation, but is used to switch to the equivalent left shift 3-bit operation, each left is equal to

Multiply 2. Accordingly, the right shift 1 bit operation corresponds to division by 2. It is worth mentioning that although the shift is fast, but

It is better to understand the code, so it is best to add some comments.

Second, JSP, EJB, JDBC

The improvement performance techniques previously described are suitable for most Java applications, and the problem to be discussed is suitable for use

Application of JSP, EJB or JDBC.

1. Use buffer marks

Some application servers have joined JSP buffer tags. For example, BEA's WebLogic Server from version 6.0

This feature supports this feature, and the Open Symphony project also supports this feature. JSP buffer tag can be slow

The flue surface is broken, and the entire page can be buffered. When the JSP page is executed, if the target piece is already in the buffer,

The code that generates the piece is not executed. Page-level buffer capture requests for the specified URL and buffer the entire result

page. This feature is extremely useful for the homepage of the shopping basket, catalog, and portal. For this type

Use, page-level buffering can save the result of the page to renew the post request.

For code logic complex pages, the effect of improving performance using buffer marks is more obvious; in turn, the effect may be slightly

Fight.

2. Always access entity beans through session beans

Direct access entity beans are not conducive to performance. When the client remotely accesses entity beans, every GET method is one

Remote call. Session beans accessing entity beans are local, able to organize all data into a structure,

Returns its value.

Access to entity beans can improve transaction management because session beans are only arrived at the transaction.

The boundary will be submitted. Each direct call to the GET method produces a transaction, the container will be in each entity bean

A "load-read" operation is performed after the transaction. Time, using entity beans will lead to poor performance.

If the unique use of entity beans is to extract and update data, it is changed to use JDBC access data within session beans.

The library can get better performance.

3. Select the appropriate reference mechanism

In a typical JSP application system, the page, the footer section is often extracted, then introduced to the page, page

foot. Currently, there are two ways to introduce external resources in the JSP page: include instructions, and include

Work.

Include directive: for example

<% @ Include file = "Copyright.html"%>

This instruction introduces the specified resource when compiling. Before compiling, pages with the include directive and the specified resource

Combined into a file. The referenced external resource is determined when compiling is more efficient than running.

Include Action: For example

This action introduces the result of the specified page execution. Since it is completed at runtime, the control of the output results

More flexible. However, only when the referenced content is frequent, or if the request on the main page is not appeared

Before, the reference page cannot be determined, using the include action is used.

4. Set read-only properties in the deployment descriptor

The deployment of the entity bean allows all GET methods to be "read only". When the work of a transaction unit is only packaged

When you have a method of performing a read operation, set the read-only property facilitates improve performance because the container does not have to perform storage exercises.

Work.

5. Buffer access to EJB HOME

The EJB HOME interface is obtained through the JNDI name. This operation requires considerable overhead. JNDI looks better

Inly in the init () method of the servlet. If you frequently appear frequently in the application, it is best to create one

EJBHomeCache class. The EJBHomeCache class should generally be implemented as a Singleton.

6. Implement local interface for EJB

The local interface is the new content of EJB 2.0 specification, which allows Bean to avoid 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 means that we have to look for the Home interface. This lookup is made through JNDI, it is a RMI adjustment

use. Then, we locate the remote object, return to the proxy reference, which is also a RMI call. The second statement demonstrates

How to create an instance involving a Stub program that creates a IIOP request and transmits a request on the network, it is also a

RMI call. To achieve a local interface, we must make the following modifications:

The method can no longer throw java.rmi.RemoteException, including exceptions derived from RemoteException,

For example TransactionRequiredException, TransactionRolledBackexception and

NosuchobjectException. EJB provides equivalent local anomalies, such as

TransactionRequiredLocalexception, TransactionRolledBackLocalexception and

NosuchObjectLocalexception.

All data and return values ​​are passed in a reference, not the transmission value. The local interface must be deployed in EJB

Use on the device. In short, the client and components of the service must run on the same JVM. If bean

The local interface is now referred to.

7. Generate the primary key

There are many ways to generate primary keys within EJBs, which analyzes several common methods and their characteristics. Use data

The library is built into the logo mechanism (SQL Server's Identity or Oracle's Sequence). The disadvantage of this method is

EJB portability is poor. The primary key value (such as incremental operation) is calculated from the entity bean. Its disadvantages are required

Serialized and the speed is slow.

Use clock services such as NTP. This requires local code for a specific platform to secure the bean to a specific

Above the OS. In addition, it also leads to such a possibility, that is, in the same millisecond on the multi-CPU server.

It became two primary keys. Borrow for Microsoft's ideas, create a GUID in the bean. However, if you do not help JNI, Java cannot determine the MAC address of the NIC; if you use JNI, the program is to depend on a specific OS.

There are several other ways, but these methods are the same limitations. It seems that only one answer is ideal: knot

Use RMI and JNDI. First bind the RMI remote object to the JNDI tree through the RMI registration. The client is performed by JNDI

Find. Below 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 a session that no longer needs in time

In order to clear the no longer active session, many application servers have default session timeout, generally 30 minutes.

When the application server needs to save more sessions, if the memory capacity is insufficient, the operating system turns some memory data.

Move to disk, the application server may also put it according to the "Most Recently UseD) algorithm

Some non-active sessions dump them to disk, and may even throw "insufficient memory" exception. In large-scale systems, strings

The cost of the vesicle session is very expensive. When the session is no longer needed, it should be called in time.

HttpSession.INVALIDATE () Method Clears the session. HttpSession.INValidate () method can usually be in

Apply exit page call.

9. Close the useless session in the JSP page

For those pages that do not have to track session status, shut down automatically created sessions can save some resources. Use the following

Page Directive:

<% @ Page session = "false"%>

10. Servlet uses memory

Many developers are free to save a lot of information into the user session. Time, the object saved in the session is not

There is a timely manner recycling. From the performance, the typical symptom is the user's sense of system cycle.

Slow, but you can't return the cause to any particular component. If you monitor the pile of JVM, its performance is memory

It is not normal to get down in normal. There are two main ways to solve such memory problems. The first way is that in all

Implement the HTTPSessionBindingListener interface with the range of the session. In this way, as long as it is realized

The valueunbound () method can explicitly release the resources used by Beans.

Another way is to invalid the session as soon as possible. Most application servers have setup sessions for waste time.

Options. In addition, you can also call the session setMaxINActiveInterval () method in a programming manner.

Used to set the maximum interval of the client requested by the servlet container before invalidating sessions.

11. HTTP Keep-Alive

Keep-alive features make the client to the server-side connection continues to be valid, when the server's subsequent request appears,

Keep-alive features Avoid establish or re-establish connections. Most of the web servers in the market, including

Iplanet, IIS, and Apache support HTTP Keep-Alive. For websites that provide static content, this

Features is usually very useful. However, there is another problem with a heavy burden, there is another problem: although guests

The household reserved has a certain advantage, but it also affects performance because the resources that can be released are still occupied during the handling of the suspension. When the web server and application server run on the same machine, Keep-

The impact of Alive features on resource utilization is especially prominent.

12. JDBC and Unicode

Mars you have learned some measures to improve performance when using JDBC, such as using connecting pools, correctly choose storage

Cheng and direct SQL, delete excess columns from the result set, pre-compiling the SQL statement, and so on. In addition to these obvious

Outside the option, another good choice for improvement may be to save all character data to Unicode

(Code page 13488). Java processes all data in Unicode, so the database driver does not have to be

Row conversion process. But should be remembered: If this is used, the database will become larger because each Unicode word

It takes 2 bytes of storage space. In addition, if there are other non-Unicode program access to the database, performance issues are still

The old will appear because the database driver still must perform a conversion process.

13. JDBC and I / O

If the application needs to access a large data set, you should consider using the block extraction method. Default

Next, JDBC extracts 32 lines of data each time. For example, suppose we want to traverse a 5000 row of records, JDBC must

You must call the database 157 to extract all the data. If the block size is changed to 512, the number of times the database is called

Will be reduced to 10 times. This technology is invalid in some cases. For example, if you use a scrollable recording set, or

The for Update is specified in the query, and the block operation is no longer valid.

14. Memory database

Many applications need to save considerable number of data in session objects in a session object, typical applications such as shopping baskets and

Directory, etc. Since this type of data can be organized in the form of rows / columns, many applications have created a huge VECTOR

Or HashMap. Saving such data in the session greatly limits the scalability of the application because the server has

There must be at least the amount of memory occupied by each session is multiplied by concurrent users, which not only makes the server price.

Expensive, and the time interval for garbage collection may also extend to an unbearable level.

Some people transfer the shopping basket / directory function to the database layer to a certain extent increase scalability. However, put this

Some functions are placed in the database layer, and the roots of the problem are the architecture of most relational database systems.

related. For relational databases, one of the important principles of runtime is to ensure that all write operations are stable.

Rely, thus, all performance issues are related to the ability to write data into the disk physically. Relationship database power map

Less I / O operation, especially for read operations, but the main way to achieve this goal is just to implement a set of buffer mechanisms.

Complex algorithm, and this is the main cause of the database layer No. 1 performance bottleneck is usually the main CPU.

A solution for an alternative to traditional relational databases is to run a database in memory (in-memory

Database, such as Timesten. The starting point of the memory database is to allow data to be temporarily written, but these data

Don't be saved permanently on the disk, all operations are in memory. In this way, the memory database does not need to be complex

Algorithm to reduce I / O operation, and can adopt a relatively simple locking mechanism, so the speed is very fast.

Third, graphical interface application

The content introduced in this article is suitable for the application of graphical user interface (Applet and normal applications), to use AWT or

Swing. 1. Use JAR compression class file

The Java file (JAR file) is a compressed file according to JavaBean standard, which is the primary and recommended ways to publish JavaBean components. JAR file helps reduce file volume and shorten the download time. For example, it helps applet

Improve the start speed. A JAR file can contain one or more related beans and support files, such as

Shape, sound, HTML, and other resources. To specify a JAR file in an HTML / JSP file, just add it in the Applet tag.

Into the Archive = "name.jar" declaration.

2. Tips Applet loading process

Have you seen the website that uses Applet, notice that a placeholder appears in a place where you should run Applet?

What happens when the applet is downloaded? The biggest possibility is that the user will go out. In this kind of

In the case, it is undoubtedly to encourage users to continue to wait for the information displayed by an applet. Let's see

Look at a specific implementation method. First create a small applet, the applet is responsible for officially downloading in the background.

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 () {

/ / Require installation of official applet

LargeAppletName = getParameter ("applet"); // "Please wait" prompt information

Label = new label ("Please wait ..." LargeAppletName);

Add (label);

}

Public void run () {

Try

{

/ / Get the class to be loaded with the applet

Class LargeAppletClass = Class.Forname (LargeAppleTname);

// Create an instance of the Applet to be loaded

Applet LargeApplet = (applet) LargeAppletClass.newInstance ();

/ / Set the APPLET STUB program

Largeapplet.setstub (this);

// Cancel "Please wait" information

REMOVE (Label);

// Set the layout

SetLayout (New GridLayout (1, 0));

Add (LargeApplet);

/ / Show formal applet

Largeapplet.init ();

Largeapplet.start ();

}

Catch (Exception EX)

{

/ / Display error message

Label.SetText ("You cannot load the specified applet");

}

// Refresh screen

Validate ();

}

Public void appletresize (int Width, int Height)

{

// Pass the AppleTResize call from the Stub program to Applet

Resize (Width, Height);

}

}

The compiled code is less than 2K, and the download speed is very fast. There are several places in the code worth noting. First, Preloader

The appletstub interface is now. Generally, Applet judges its own codeBase from the caller. In this example, we

You must call SetStub () tell the Applet where to extract this information. Another thing that is worth noting is that the AppletStub interface contains many ways with the Applet class, except for the AppleTResize () method. Here I am

They pass the call to the AppleTResize () method to the Resize () method.

3. Put it in advance before drawing the graph

ImageOBserver interface can be used to receive prompt information for graphics. ImageObserver interface has only one way

ImageUpdate (), can draw a graphic 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;

}

When graphics information is available, the ImageUpdate () method is called. This method returns if further updating needs to be updated.

TRUE; if the required information has been obtained, the method returns false.

4. Cover 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 ()

Methods, frequent use of graphics can display flicker. To avoid clearing the screen before the Paint () call

In addition to the operation, you only need to override the Update () method as follows:

Public void Update (graphics g) {

Paint (g);

}

The more ideal solution is to override Update (), only the area that changes on the screen, as shown below:

Public void Update (graphics g) {

g.ClipRect (x, y, w, h);

Paint (g);

}

5. Delayed redrawing operation

For the application of the graphical user interface, the main reason for performance is often the efficiency of the heavy picture screen.

under. This is usually obvious that the user changes the window size or scrolls one window. change

Window size or scrolling operations such as scrolling screens lead to a large number of heavy-screen events, generate quickly, even more than

The execution speed of the relevant code. The best way to deal with this problem is to ignore all "late" events.

It is recommended to introduce a few milliseconds here, that is, if we immediately receive another heavy-in event, you can stop

Treatment of the current event to handle the last heavy draw event; otherwise, we continue to play the current heavy painting

Process.

If the event is to start a time consuming, it is a good way to handle a work thread; otherwise,

Some parts may be "freeze" because only one event can be handled each time. The following provides an emptive

Single example, but it can be used to control the working thread after expansion.

Public Static Void Runonce (String ID, Final Long MilliseConds) {

SYNCHRONIZED (E_QUEUE) {

// E_QUEUE: Collection of all events

IF (! E_QUE.CONTAINSKEY (ID)) {

e_queue.put (token, new lastone ());

}

}

Final lastone lastone = (lastone) E_QUEUE.GET (TOKEN);

Final long time = system.currenttimemillis (); // Get the current time lastone.time = time;

(new thread () {public void run () {

IF (MilliseConds> 0) {

Try {thread.sleep (MilliseConds);} // Term thread

Catch (Exception EX) {}

}

Synchronized (Lastone.Running) {// Waiting for the last event end

IF (Lastone.Time! = Time) // only handle the last event

Return;

}

}}). START ();

}

Private static hashtable e_queue = new hashtable (); private stataint class

Lastone {

Public long time = 0;

Public Object Running = New Object ();

}

6. Use a double buffer

A buffer drawing outside the screen, and immediately display the entire graph immediately after completion. Since there are two buffers,

The program can switch back and forth. In this way, we can use a low priority thread to draw, so that the program can benefit

Perform other tasks with idle CPU times. The pseudo code fragment below demonstrates this technology.

Graphics mygraphics;

Image myoffscreenimage = createImage (size (). Width, size (). Height);

Graphics offscreengraphics = myoffscreenimage.Graphics ();

OFFSCREENGRAPHICS.DRAWIMAGE (IMG, 50, 50, THIS);

MyGraphics.drawImage (MyoffScreenimage, 0, 0, this);

7. Using BufferedImage

Java JDK 1.2 uses a soft display device that makes text look similar on different platforms. This is true

Features, Java must directly process pixels constituting text. Since this technology is to be done in the memory

Operation, early JDK is in poor performance when using this technology. Realization of Java standards proposed to solve this problem

A new graphic type, is bufferedimage. BufferedImage subclass description graphic with a visible

The graphics data buffer is asked. A bufferedImage contains a ColorModel and a set of raster graphics data. This

A class typically uses RGB (red, green, blue) color model, but also handles grayscale graphics. Its constructor is very

Simple, as shown below:

Public BufferedImage (int Width, Int Height, int imagetype)

ImageType allows us to specify what type of graphic to buffer, such as 5-bit RGB, 8-bit RGB, grayscale

Wait.

8. Using VolatileImage

Many hardware platforms and their operating systems provide basic hardware acceleration support. For example, hardware acceleration is generally provided

The rectangular fill function, and the hardware acceleration is more efficient than using the CPU to complete the same task. Due to hardware acceleration

A portion of the work, allowing multiple workflows to be carried out, thereby alleviating the pressure on the CPU and system bus, so that

It is faster to run. Use VolatileImage to create hardware accelerated graphics and the content of management graphics.

Since it directly uses the ability to use low-level platforms, the degree of improvement in performance depends primarily on the graphical adapter used by the system.

The content of VolatileImage may be lost at any time, that is, it is "Volatile". Therefore, it is best to check if its content is lost before using the graph. VolatileImage has two to check whether the content is

Lost method:

Public Abstract Int Validate (GraphicsConfiguration GC); Public Abstract

Boolean contentslost ();

You should call the Validate () party each time you copy content or write VolatileImage from the VolatileImage object.

law. The contentslost () method tells us that since the last validate () call, the content of the graphics is

No loss. Although VolatileImage is an abstract class, don't send a child class from it. VolatileImage

Should be component.createvolatileImage () or

GraphicsConfiguration.createCompaTibleVolatileImage () method is created.

9. Using Window Blitting

When scrolling operation, all visible content generally want to scroll, resulting in a lot of unnecessary heavy paintings. Xu

Multi-operating system graphic subsystem, including Win32 GDI, MacOS, and X / Windows, support Window

BLITTING technology. Window Blitting technology moves the graphics directly to the new position in the screen buffer, only redraw

A new area. To use Window Blitting technology in Swing applications, the setting method is as follows:

SetscrollMode (int mode);

In most applications, this technique can be used to improve scrolling speed. Only in one case, Window

Blitting can result in a decrease in performance, that is, the application is scrolling in the background. If the user is scrolling an application,

Then it is always at the front desk, there is no need to worry about any negative impact.

转载请注明原文地址:https://www.9cbs.com/read-37717.html

New Post(0)