Digital Edition

Extreme Performance Tuning
Extreme Performance Tuning

Many development shops have used J2EE to build a successful business-logic tier but have fallen short on obtaining the desired look and feel. On my current project we considered using applets as substitutes for GIF-based buttons, creating a utility to modify tree-based structure data as well as an application that will allow a secure file-based transmission. In my spare time I'm also working on an idea for a video game. All of these require an architecture that takes performance into consideration.

Performance tuning is an integral part of any Java-based application development effort. It's vitally important for the users of your program to think that it performs well. In Parts 1 and 2 (JDJ, Vol. 6, issues 9 and 10), we focused on tips that are geared toward making J2EE-based applications run faster and scale better. Part 3 focuses on making programs that are graphical in nature (applets and applications) and utilize either Swing or AWT to become extremely scalable.

Always JAR Classes
A Java Archive (JAR) is a file that has been compressed according to the JavaBeans standard. It's the primary and recommended method for delivering JavaBean components. It helps reduce file sizes and download times, which may make your applets appear faster. A JAR file can contain one or more related beans, support files such as graphics, sounds, HTML, and other resources.

To specify a JAR file within an HTML/JSP file, add the variable ARCHIVE = "name.jar" to the applet tags.

Consider Using Delegated Loading
Have you ever visited a Web site that uses Java applets and noticed that your browser puts a placeholder where the Java applet is supposed to run? What happens when the applet takes a significant time to load? The most likely answer is that the user goes to another site. In this scenario it would be useful to display a message that the applet is being loaded and he or she should stick around.

Let's discuss one technique that can help you realize this goal. First you need to create a very small applet that downloads the real applet in the background. Let's stub out some code snippets that show how this can be accomplished (see Listing 1).

The compiled code should be less than 2K so it downloads quickly. In looking at this code in Listing 1 you'll notice a couple of subtle items. First we implement AppletStub. Typically an applet determines its code base from the caller. In our scenario we have to tell the applet where to retrieve this information by calling setStub. The other notable difference is that the AppletStub interface implements many of the same methods in the Applet class, except for AppletResize. We're delegating the AppletResize method to the resize method.

Always Set the Display Mode
Setting the display mode within an AWT-based application allows your program to run quicker if the images it chooses to display share the same bit-depth as the screen. An added advantage of setting the display mode comes when you know the display size in advance, as you won't have to programmatically scale images up or down depending on the display. Note: In some environments you can only change the display mode when in full-screen exclusive mode.

You can determine the current display mode by calling java.awt.getDisplayMode() as well as a list of all supported modes by calling java.awt.getDisplayModes(). To set the display mode you need to pass the width and height of the monitor in pixels, bit depth (number of bits per pixel), and refresh rate (how often the monitor updates itself). Listing 2 demonstrates setting the display mode.

Full-screen exclusive mode is handled through a java.awt.GraphicsDevice object. This particular object exposed another useful method, isFullScreenSupported(), which determines if full-screen exclusive mode is available. It's possible to still set full-screen mode on a system that doesn't support it. The outcome may be performance degradation. In this scenario it may be better to run the application in a windowed mode with a fixed size rather than setting a full-screen window.

Consider Preloading Images Before Painting
The ImageObserver interface can be used to receive notification when an image is being loaded. The ImageObserver interface has only one method, imageUpdate(), which can be used to paint the image on the screen in a single repaint. Listing 3 provides a technique for doing this.

The ImageUpdate method is called when information about an image becomes available. This method returns true when further updates are needed and false if the required information has been obtained.

Always Override Update
The default behavior of update is to clear the screen of all content and call the paint() method. Applications that are heavy in graphics will display a flickering behavior when using the default behavior.

To prevent the clearing of the screen before paint is called, you can override update() simply as follows:

Public void update(Graphics g) {

An even better method would be to override the update() method and paint only the region of the screen where changes will take place. Here's a better example:

Public void update(Graphics g) {
     g.clipRect(x, y, w, h);

Consider Delaying Redrawing
The main reason for performance degradation in a graphical-based application can be traced back to inefficient redrawing. This is usually noticed when a user resizes and/or scrolls a window. This behavior causes redraw events to be generated faster than the redraw can execute. The best way to handle this deficiency is to ignore all events that arrive too late.

One technique that can help is to draw to a large off-screen buffer (explained later). The redraw event listener can copy parts of a bitmap. This technique will work in some situations, but wouldn't be useful in any situation where image dimensions actually change, such as 3D rotation. Another technique may be to have the redraw event listener block further redraws until the current one finishes. We could essentially take the last received redraw event and discard all others.

I recommend introducing a couple of milliseconds into the equation so that if we immediately receive another redraw event, we can stop our current event and process the last redraw received; otherwise, we continue with the current redraw.

Listing 4 demonstrates a simple technique for handling events but could be expanded to handle worker threads. It's usually a good idea to spawn a worker thread whenever an event initiates time-consuming tasks. Otherwise, all components will freeze as only one event can occur at a time.

Always Double Buffer
Draw your images off screen and then display an entire image at once. There are two buffers and you can switch between them. This allows you to offload the drawing of the display image to the background using a lower-priority thread, making your program use unused clock cycles. Here's a quick code snippet that displays the technique:

Graphics graphics;
Image offscreenImage = createImage(size().width, size().height);
Graphics offscreenGraphics = offscreenImage.getGraphics();

offscreenGraphics.drawImage(img, 50, 50, this);
graphics.drawImage(offscreenImage, 0, 0, this);

Use BufferedImage
Java JDK 1.2 uses a software renderer so that text appears similar across platforms. The implementation of this function requires direct access to the pixels that form the text. Prior JDKs had performance issues with this technique as it involved copying lots of bits around in memory. The Java specification to handle this particular performance problem implemented a new image type, BufferedImage.

The BufferedImage subclass describes an image with an accessible buffer of image data. A BufferedImage is comprised of a ColorModel and a raster of image data. This class typically uses the RGB (red, green, blue) color model but can also handle grayscale. The constructor is straightforward and looks like:

Public BufferedImage (int width, int height, int imageType)

ImageType allows us to specify the actual type of image we want to buffer such as 5-bit RGB, 8-bit RGB, grayscale, and so forth.

Consider Using VolatileImage
Many hardware platforms and their respective operating systems support basic hardware acceleration. Hardware acceleration typically provides rectangle filling that's faster than having the CPU perform the function in an offloaded fashion. The ability to offload work and have parallel streams of work happening concurrently frees up the CPU and systems bus. This also allows for nongraphics related functionality to occur, making the application faster.

VolatileImage allows applications to create hardware-accelerated, off-screen images as well as manage its contents. Since this feature takes advantage of the underlying platform's capabilities, performance increases depend primarily on the graphics adapter in use.

VolatileImages can be lost at any time, hence they're volatile; it's a good idea to check for loss of content before using the image. The VolatileImage has two methods to test for content loss:

Public abstract int validate(GraphicsConfiguration gc);
Public abstract Boolean contentsLost();

The validate() method should be called whenever copying from or rendering to a VolatileImage object. The contentsLost() method tells the program if the contents of the image have been lost since the last call to validate().

Although VolatileImage is an abstract class, don't subclass from it. VolatileImage should always be created by calling Component.create- VolatileImage().

Consider Using Window Blitting
Typically when a user scrolls, the entire visible contents are redrawn. This may cause a lot of redrawing work for no good reason. Window blitting is used by many graphical OS subsystems, including the WIN32 GDI, MacOS, and X/Windows. It moves bits directly from the screen buffer to their new location when scrolling. This technique updates only the newly exposed area. To enable window blitting for your Swing-based application, use the following method:

setScrollMode(int mode);

Using this technique will increase scrolling performance in most applications. The only type of application that I'm aware of where this technique will cause a performance decrease is when the scrolling application is being scrolled in the background. If the user is scrolling the application, it will always be in the foreground and you don't have anything to worry about.

I hope this article has been useful and you get the opportunity to try some of the recommended techniques.

About James McGovern
James McGovern is an industry thought leader and the author of the bestselling book: A Practical Guide to Enterprise Architecture (Prentice Hall). He is working on two upcoming books entitled: Agile Enterprise Architecture and Enterprise SOA. He is employed as an Enterprise Architect for The Hartford Financial Services Group, Inc. He holds industry certifications from Microsoft, Cisco and Sun. He is member of the Java Community Process and of the Worldwide Institute of Software Architects.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Subscribe to the World's Most Powerful Newsletters


The explosion of new web/cloud/IoT-based applications and the data they generate are transforming ou...
CI/CD is conceptually straightforward, yet often technically intricate to implement since it require...
Containers and Kubernetes allow for code portability across on-premise VMs, bare metal, or multiple ...
Enterprises are striving to become digital businesses for differentiated innovation and customer-cen...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As au...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't com...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, wi...
The now mainstream platform changes stemming from the first Internet boom brought many changes but d...
DXWorldEXPO LLC announced today that Ed Featherston has been named the "Tech Chair" of "FinTechEXPO ...
Chris Matthieu is the President & CEO of Computes, inc. He brings 30 years of experience in developm...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: D...
Andi Mann, Chief Technology Advocate at Splunk, is an accomplished digital business executive with e...
In this presentation, you will learn first hand what works and what doesn't while architecting and d...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitori...
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use ...
If your cloud deployment is on AWS with predictable workloads, Reserved Instances (RIs) can provide ...
Disruption, Innovation, Artificial Intelligence and Machine Learning, Leadership and Management hear...
We build IoT infrastructure products - when you have to integrate different devices, different syste...
Consumer-driven contracts are an essential part of a mature microservice testing portfolio enabling ...