A collection of Java performance optimization techniques (2)

Source: Internet
Author: User
Tags abstract continue current time final interface static class stub thread
Skills | performance | Optimization three, GUI article

This section covers the application of the graphical user interface (applets and general applications) to use AWT or swing.

3.1 Compressing class files with jars

A Java archive (JAR file) is a file that is compressed according to the JavaBean Standard and is the primary way and recommended way to publish JavaBean components. Jar files help reduce file volume and shorten download time. For example, it helps applets improve startup speed. A jar file can contain one or more related beans and supporting files, such as graphics, sounds, HTML, and other resources.

To specify a jar file in the html/jsp file, simply add the archive = "Name.jar" declaration to the applet tag.

See "Using profiles to increase the loading speed of applets".

3.2 Prompts the applet to mount the process

Have you ever seen a Web site that uses applets, and noticed that a placeholder appears where you should run the applet? What happens when the applet downloads for a long time? The biggest possibility is that users will turn around and leave. In this case, displaying the information an applet is downloading undoubtedly helps to encourage the user to continue waiting.

Now let's take a look at a specific implementation method. Start by creating a small applet that is responsible for downloading the formal applets in the background:


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 () {
Formal applets required for loading
Largeappletname = GetParameter ("applet");
"Please wait" message
Label = new label ("Please wait ..." + largeappletname);
Add (label);
}
public void Run () {
try {
Get classes to load applets
Class Largeappletclass = Class.forName (largeappletname);
Create an instance of an applet to be loaded
Applet Largeapplet = (applet) largeappletclass.newinstance ();
Set stub program for this applet
Largeapplet.setstub (this);
Cancel the "Please wait" message
Remove (label);
Set layout
SetLayout (New GridLayout (1, 0));
Add (Largeapplet);
Show the Formal applet
Largeapplet.init ();
Largeapplet.start ();
}
catch (Exception ex) {
Display error messages
Label.settext ("Cannot load the specified applet");
}
Refresh Screen
Validate ();
}
public void appletresize (int width, int height) {
Pass the Appletresize call from the stub program to the Applet
Resize (width, height);
}
}



The compiled code is less than 2K and the download speed is fast. There are several places in the code that deserve attention. First, the Preloader implements the Appletstub interface. In general, applets judge their own codebase from the caller. In this case, we have to call Setstub () to tell the applet where to extract this information. Another noteworthy point is that the Appletstub interface contains many of the same methods as the Applet class, except for the Appletresize () method. Here we pass the call to the Appletresize () method to the Resize () method.

3.3 Pre-loading the graphic before drawing it

The ImageObserver interface can be used to receive hints about graphics loading. The ImageObserver interface has only one method Imageupdate (), capable of drawing graphics on the screen with a repaint () operation at a time. 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;
File not found, consider displaying a placeholder
Repaint ();
}
Return (Flags & Allbits | error| ABORT) = = 0;
}



The Imageupdate () method is invoked when the graphic information is available. This method returns true if further updates are required, and false if the required information has been obtained.

3.4 Overwrite Update method

The default action for the update () method is to clear the screen and then invoke the paint () method. If you use the default update () method, applications that use graphics frequently may display flicker. To avoid screen cleanup before the paint () call, simply overwrite the update () method as follows:


public void Update (Graphics g) {
Paint (g);
}



A more desirable scenario would be to overwrite update () and only redraw the changed area of the screen as follows:


public void Update (Graphics g) {
G.cliprect (x, Y, W, h);
Paint (g);
}



3.5 Deferred repaint operation

For the application of graphical user interface, the main reason of low performance often boils down to the inefficiency of painting screen. This can often be observed when the user changes the window size or scrolls through a window. Actions such as changing the window size or scrolling the screen cause the redraw screen events to generate massively, quickly, or even exceed the execution speed of the associated code. The best way to deal with this problem is to ignore all "late" events.

It is recommended to introduce a millisecond time difference here, that is, if we receive another redraw event immediately, we can stop processing the current event instead of the last one received, otherwise we continue with the current redraw process.

If an event is to start a time-consuming task, separating a worker thread is a good way to do it; otherwise, some parts may be "Frozen" because only one event can be processed at a time. A simple example of event handling is provided below, but it can be used to control worker threads after it has been extended.


public static void RunOnce (String ID, final long milliseconds) {
Synchronized (e_queue) {//E_queue: Collection of all events
if (!e_queue.containskey (ID)) {
E_queue.put (token, new LaStone ());
}
}
Final LaStone LaStone = (lastone) e_queue.get (token);
Final long time = System.currenttimemillis (); Get current time
Lastone.time = time;
(New Thread () {public void run () {
if (milliseconds > 0) {
try {thread.sleep (milliseconds);}//Pause thread
catch (Exception ex) {}
}
Synchronized (lastone.running) {//Waiting for the last event to end
if (lastone.time!= time)//Only the last event is processed
Return
}
}). Start ();
}
private static Hashtable E_queue = new Hashtable ();
private Static Class LaStone {
public long time=0;
Public Object running = new Object ();
}



3.6 Using double buffers

Draw the buffer outside the screen and display the entire graphic as soon as it is finished. Because there are two buffers, the program can switch back and forth. In this way, we can use a low priority thread to paint, allowing the program to take advantage of idle CPU time to perform other tasks. The following pseudocode snippet demonstrates this technique.


Graphics Mygraphics;
Image myoffscreenimage = createimage (Size (). width, size (). height);
Graphics offscreengraphics = Myoffscreenimage.getgraphics ();
Offscreengraphics.drawimage (IMG, M, this);
Mygraphics.drawimage (myoffscreenimage, 0, 0, this);



3.7 Using BufferedImage

Java JDK 1.2 uses a soft display device that makes text look similar on different platforms. To implement this functionality, Java must directly handle the pixels that make up text. Because of the large amount of bit-copying operations in memory, the early JDK had poor performance in using the technology. The Java standard proposed to solve this problem implements a new type of graphics, namely BufferedImage.

The graph described by the BufferedImage subclass has an accessible graphics data buffer. A bufferedimage contains a ColorModel and a set of raster graphics data. This class generally uses an RGB (red, green, blue) color model, but it can also handle grayscale graphics. Its constructor is simple, as follows:


public bufferedimage (int width, int height, int imagetype)



ImageType allows us to specify what type of graphics to buffer, such as 5-bit RGB, 8-bit RGB, gray level, and so on.

3.8 Using Volatileimage

Many hardware platforms and their operating systems provide basic hardware acceleration support. For example, hardware acceleration generally provides rectangular padding, and hardware acceleration is more efficient than using the CPU to accomplish the same task. Since hardware acceleration separates a part of the work, allowing multiple workflows to be performed concurrently, relieving the pressure on the CPU and system bus so that applications can run faster. With Volatileimage, you can create graphics for hardware acceleration and manage the content of graphics. Because it directly utilizes the capabilities of the lower platform, the performance improvement depends largely on the graphics adapter used by the system. The content of the volatileimage may be lost at any time, i.e. it is "unstable" (volatile). So before you use graphics, it's a good idea to check that the content is missing. Volatileimage has two ways to check whether the content is missing:


public abstract int Validate (graphicsconfiguration GC);
Public abstract Boolean contentslost ();



Each time you copy content from a Volatileimage object or write to Volatileimage, you should call the Validate () method. The Contentslost () method tells us whether the contents of the graphic have been lost since the last validate () call.

Although Volatileimage is an abstract class, do not derive subclasses from it. Volatileimage should be created through the component.createvolatileimage () or Graphicsconfiguration.createcompatiblevolatileimage () method.

3.9 using Window blitting

When scrolling, all the visible content is typically repaint, resulting in a large amount of unnecessary repaint work. The graphics subsystems of many operating systems, including WIN32 GDI, MacOS, and x/windows, Support window blitting technology. The Window blitting technology moves the graphic to a new location directly in the screen buffer, only to redraw the newly-appearing area. To use window blitting technology in swing applications, set the method as follows:


Setscrollmode (int mode);



In most applications, the use of this technique can improve scrolling speed. Only in one case, Window blitting can cause performance degradation, that is, the application is scrolling in the background. If the user is rolling an application, then it is always in the foreground, without worrying about any negative effects.

Iv. Additional Information



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.