HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

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) {
paint(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);
paint(g);
}

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.createVolatileImage().

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.

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

Author Bio
James McGovern is an enterprise architect with Hartford Technology Services Company’ L.L.C., an information technology services firm dedicated to helping businesses gain competitive advantage through the use of technology. His focus is on developing extremely scalable Internet applications. [email protected]

	



Listing 1



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 appletToLoad;
  Label label;
  Thread appletThread;
 public void init() {
  // This is the applet we want to delay 
  loading
  appletToLoad = getParameter("applet");
  label = new Label("Stay tuned" + appletToLoad);
  add(label);
  }
 public void run(){
  try {
  // Get the class 
  of the real applet
  Class appletClass 
  = Class.forName(appletToLoad);
 // Create an instance 
  of the real applet
  Applet realApplet = (Applet)appletClass.newInstance();
 // Set the stub 
  for the applet
  realApplet.setStub(this);
 // Get rid of 
  the Stay Tuned message
  remove(label);
 // Maximize the applet 
  to the current size
  setLayout(new GridLayout(1, 
  0));
  add(realApplet);
 // Lets now display 
  the real applet
  realApplet.init();
  realApplet.start();
  }
  catch (Exception ex) {
  // Display an error
  label.setText("Error loading 
  applet.");
  }
 // We need to redraw the screen
  validate();
  }
 public void appletResize(int width, int height) {
  // Transfer the call of 
  AppletResize from the stub to the applet.
  resize(width, height);
  }
  }
  
 Listing 2
GraphicsDevice aDevice;
Windows aWindow;
DisplayMode newDisplayMode;
DisplayMode oldDisplayMode = aDevice.getDisplayMode();
 try {
  aDevice.setFullScreenWindow(aWindow);
  aDevice.setDisplayMode(newDisplayMode);
  // do rest of work
  }
  finally {
  aDevice.setDisplayMode(oldDisplayMode);
  aDevice.setFullscreenWindow(null);
  
 Listing 3
 public boolean imageUpdate(Image img, int flags, int x, int y, int w, int 
  h) {
  if ((flags & ALLBITS) 
  !=0 {
  repaint();
  }
  else if (flags & 
  (ABORT | ERROR)) != 0) {
  error 
  = true;
  // 
  File was not found so consider displaying placeholder
  repaint();
  }
  return (flags 
  & (ALLBITS | ABORT | ERROR)) == 0;
  }
  
 Listing 4
 public static void runOnce(String id, final long milliseconds) {
  synchronized(s_queue) 
  { // s_queue is a collection of all events
  if 
  (!s_queue.containsKey(id)) {
  s_queue.put(token, 
  new Latest());
  }
  }
 final Latest 
  latest = (Latest) s_queue.get(token);
  final long 
  time = System.currentTimeMillis(); // Get current time
  lastest.time 
  = time;
 (new Thread() 
  {public void run() {
  if 
  (milliseconds > 0) {
  try 
  {Thread.sleep(milliseconds);} // Sleep for a little bit
  catch 
  (Exception ex) {}
  }
  synchronized(lastest.running) 
  { // Wait until previous finishes
  if 
  (latest.time != time) // Only run latest
  return;
  }
  }}).start();
  }


private static Hashtable s_queue = new Hashtable();
 private static class Latest {
  public long time=0;
  public Object running = new 
  Object();
  }

  
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.