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

I'm sure we've all heard it before: Java on the client is slow; Swing is slow. The reality is that Sun has made great progress in increasing the speed of Swing and Java on the client.

However, it's up to developers to demonstrate that Java has indeed improved to the point of usability and viability on the client.

To do this, the code needs to be very lean and clean. One of the original problems with GUI creation was the reliance upon Visual Development Tools to design and code the GUI. While these VDTs have come a long way in the last few years, I have found that many developers rely so heavily on the VDTs that they've gotten lazy when it comes to coding the actual functionality of the application.

The Problem
Methods are expensive in terms of execution time. The more method calls made, the slower the application will be. However, there needs to be a balance between speed of execution and good coding standards.

Swing makes a large number of method calls during its startup and execution. This is a price that has to be paid for its design model. What compounds the method calls that Swing requires is the number of method calls the average developer piles on top of Swing.

Multithreading Swing
The Swing API is considered to be single threaded and thread "unsafe." However, for a Swing GUI to be responsive, some actions must be threaded, such as database access.

In a normal GUI construction, if a call to a database is made, the GUI will just sit there waiting for the database access to return. Not only will the GUI be unresponsive, it won't even repaint! This can cause the user to believe the application has locked up or failed in some way. This problem is not unique to Java. Every GUI API has to deal with this same issue in some fashion. It's unfortunate that many Java Swing developers don't handle this type of situation properly.

Steve Wilson of Sun Microsystems is quoted as saying that in any situation where it's known that the process is going to take a long time, a GUI should respond to the user in some fashion within 50 milliseconds. Any slower than this and it will feel sluggish. Naturally a database request is not going to return in 50 milliseconds or less! This is where multithreading comes into play. The problem lies in properly threading your Swing GUI application to avoid complications with Swing's single-threaded nature.

The solution to this problem lies within two methods: invokeLater and invokeAndWait. These two methods were originally in the SwingUtilities class but, as of v1.2, they've been moved to the java.awt.EventQueue class. Applications can still call these methods in the SwingUtilities class but are merely wrappers for the java.awt methods.

Listing 1 demonstrates database access being spun off into a separate thread. The method that's called is invokeAndWait, which means the worker thread is blocked until the database activity returns. However, the GUI's thread is not blocked and will allow repaints, and more. Note: This is a very primitive example designed to only show the multithreading.

Once the database call has returned, it's time to update the GUI. Since this is still in a separate thread, it won't modify the GUI directly. Thus, in Listing 1, all the GUI updating is in a call to the invokeLater method. This method doesn't block the worker thread that allows it to terminate peacefully. The work to update the GUI has been placed into the event queue, and once it reaches the top of the heap, the GUI will be updated. This allows the update to the GUI to happen from a thread outside the event thread without causing problems.

Model, View, Control
Example 1: JTable
The cleanest way to solve this problem is to write Swing code by hand as it provides two clear benefits:
1.  The code will be very lean and clean.
2.  The code will be much easier to maintain since there will be fewer method calls in the code.

For example, consider a simple JFrame with a few buttons and a table on it. Any complex GUI will generally be using GridBagLayout as its layout manager, therefore this example will be using GBL as the layout manager. Hopefully, through this example, you'll see a reduction in the lines of code, enabling you to write cleaner, tighter, and better performing GUI code.

Listing 2 shows an example GUI built using JBuilder's VDT. I'll admit I was very impressed at how compact the code was that JBuilder produced. There's very little improvement that can be done at this point. However, looking at Listing 3, you can see that we were able to remove a few method calls. The calls to setText() have been moved into the constructor calls for the buttons. The other change we can see at this point is excess construction of GridBagConstraints objects. This is excessive due to what the GridBagLayout does with these objects.

When the GridBagConstraints is passed into the GridBagLayout, the first thing that's done is it's cloned. The GridBagLayout does this so that the GridBagConstraints doesn't change on it unexpectedly. Thus, the individual creation of GridBagConstraints here is unnecessary. This is why, in Listing 4, there's only one GridBagConstraints and it's modified for each call to the JPanel's add method.

Both of these changes are relatively minor and won't improve the performance all that noticeably. However, this is where the VDT stops and the developer takes over.

It's very common for a developer to utilize the shortcuts in the creation of a JTable to populate it for data. While these shorten the development cycle slightly, they'll cost a fortune in performance. Instead, the creation of an actual table model that's customized for a specific use will improve performance. By implementing your own TableModel, you can reduce the number of method calls and object creations that are normally incurred when using the default models.

For example, take a JTable created with the (Vector, Vector) constructor. The only way you can access that data programmatically is via those vectors. However, the GUI doesn't know if anything has changed inside those vectors and therefore needs to be informed of the change so the GUI can repaint itself. However, if a custom TableModel object is created that's specifically designed to handle the data you wish to represent, you're able to add methods directly to the model that will allow you to edit the data and then fire off an event that the View will intercept and handle. This eliminates a large number of method calls and indirection in your code and indirectly increases the performance of your GUI overall.

Listing 4 is an example TableModel implementing the various methods that are required. Notice that the example extends from the AbstractTableModel. There are a few nonrequired methods in the AbstractTableModel that are useful and don't need to be replaced. This allows the AbstractTableModel to handle the listeners and deal with delivering the events that you create. This leaves us with the methods shown in Table 1.

Table 1

Our example is fairly simple but it gives you an idea of how you could construct a TableModel specifically tailored to the data it will be representing. It's a rare situation indeed where you will need to display completely dynamic data.

Example 2: JTree
Another area of performance contention is the JTree API. In a large number of cases where I've seen the JTree used in a production environment, it's invariably used incorrectly, causing the number of objects involved with it to double.

The JTree API is designed around the concept of nodes; each point in the tree is either a branch or a leaf. Every point in the JTree implements the TreeNode interface. This interface defines methods inside it that tell the View whether or not that particular node is a leaf or a branch.

What happens is that developers tend to use (read overuse) the DefaultMutableTreeNode class instead of developing their own TreeNodes. This produces a "wrapper" class around their actual data that causes a doubling of the number of classes in the JTree. While this certainly works (even the tutorials from Sun do this), it's not the most efficient way to handle a JTree.

To remove this doubling of objects in the tree, one of two things can be done:
1.  Don't use any data objects inside the DefaultMutableTreeNode.
2.  Have your data objects that are going to be represented by a tree implement TreeNode.

Clearly, not putting any of your data objects in the tree is self-defeating, so we'll explore the second option - implementing the TreeNode interface. We don't need to implement the actual model since the default model expects and knows how to handle the TreeNode interface. Thus our data objects that will be displayed in the Tree need to implement the methods shown in Table 2.

Table 2

None of these methods impact the data you're representing and they have very little to do with the GUI. Thus your design integrity stays intact. However, this allows you to modify the data directly, notify the model that the data has changed, and not have to go through an intermediary layer and deal with casting from Object, and so on. This eliminates numerous method calls and the creation of objects that serve very little purpose.

The Swing API is more complicated than other graphical APIs on the market. A large portion of this is attributed to the Model-View-Control design pattern. However, as developers we can avoid compounding the complexity of Swing by reducing the amount of code that we lay on top of it.

When you go through the optimization phase of your project, look at each method dealing with the GUI and see if there are any method calls that you can remove, any objects that are unnecessary, and any objects you can avoid creating by implementing the model interfaces yourself instead of creating wrapper objects. Once that's complete, start looking for operations that take a long time and consider putting them into separate worker threads instead of the primary GUI thread.

These simple steps will dramatically improve the performance of Swing while still adhering to the OO paradigm as well as the single-threaded rules.


  • The Swing Connection: http://java.sun.com/products/jfc/tsc/
  • Java Platform Performance: Strategies and Tactics: http://developer.java.sun.com/ developer/Books/performance/
  • Christmas Tree Applications: http://java.sun.com/products/jfc/tsc/ articles/ChristmasTree/

    About The Author
    Marcus S. Zarra is the director of technology at Extraquest Corporation in Denver, Colorado. He began developing professionally in 1985 for school systems and then for legal firms in Phoenix, Arizona. Marcus has been a Java developer since 1996, working in the banking, telecommunications, and insurance industries. [email protected]

    "Trimming the Fat from Swing"
    Vol. 8, Issue 7, p. 34

    Listing 1
    1   Thread worker = new Thread() {
    2     public void run() {
    3       //Do the database work here
    4       Runnable r = new Runnable() {
    5         public void run() {
    6           //Update the GUI with 
                  the data
    7         }
    8       };
    9       SwingUtilities.invokeLater(r);
    10    }
    11  };
    12  worker.start();
    Listing 2
    1  jButton1.setText("jButton1");
    2  this.getContentPane().setLayout(
    3  jButton2.setText("jButton2");
    4  this.getContentPane().add(jButton1, 
        new GridBagConstraints(0, 1, 1, 
        1, 1.0, 0.0, 
        GridBagConstraints.NONE, new 
        Insets(0, 0, 0, 0), 0, 0));
    5  this.getContentPane().add(jButton2, 
        new GridBagConstraints(1, 1, 1, 
        1, 1.0, 0.0, 
        new Insets(0, 0, 0, 0), 0, 0));
    6  this.getContentPane().add(jTable1, 
        new GridBagConstraints(0, 0, 2, 
        1, 1.0, 1.0, 
        new Insets(0, 0, 0, 0), 0, 0));
    Listing 3
    1  jButton1.setText("jButton1");
    2  jButton2.setText("jButton2");
    3  getContentPane().setLayout(
        new GridBagLayout());
    4  GridBagConstraints gbc = 
        new GridBagConstraints();
    5  gbc.gridx = 
    6  gbc.gridy = 0;
    7  gbc.gridwidth = 2;
    8  gbc.weightx = 1.0;
    9  gbc.weighty = 1.0;
    10 getContentPane().add(jTable1, gbc);
    11 gbc.gridy++;
    12 gbc.gridwidth=1;
    13 gbc.weightx = 0.0;
    14 gbc.weighty = 0.0;
    15 getContentPane().add(jButton1, 
    16 getContentPane().add(jButton2, 
    Listing 4
    1  public class ExampleTM 
        extends AbstractTableModel {
    2    private String columnNames[] = 
          {"Widget Name", "Cost", 
           "Available", "Quantity"};
    3    private Vector widgets;
    4    public ExampleTM(Vector w) {
    5      widgets = w;
    6    }
    7    public Class getColumnClass(
         int c) {
    8      switch (c) {
    9        case 0:
    10         return String.class;
    11       case 1:
    12         return Double.class;
    13       case 2:
    14         return Boolean.class;
    15       case 3:
    16         return int.class;
    17     }
    18   }
    19   public int getColumnCount() {
    20     return 4;
    21   }
    22   public int getColumnName(
         int c) {
    23     return columnNames[c];
    24   }
    25   public int getRowCount() {
    26     return widgets.size();
    27   }
    28   public Object getValueAt(int r, 
         int c) {
    29     Widget w = (Widget) 
    30     switch (c){
    31       case 0:
    32         return w.getName();
    33       case 1:
    34         return w.getCost();
    35       case 2:
    36         return w.isAvailable();
    37       case 3:
    38         return w.getQuantity();
    39       default: 
    40         return null;
    41     }
    42   }
    43   public boolean isCellEditable(
           int r, int c) {
    44     return false;
    45   }
    46 }

    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.