The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Using Other Swing Features

How to Use Threads

This section assumes that you are familiar with threads — lightweight processes that can run concurrently. If you are unfamiliar with threads, you can read Threads: Doing Two or More Tasks At Once (in the Creating a GUI with JFC/Swing trail).

This section discusses two aspects of thread usage. We first discuss threads as it applies to every Swing application — namely, why all code that deals with components needs to execute on a specific thread. We also discuss the invokeLater and invokeAndWait methods, which are used to ensure that code executes on this special thread. The rest of the section applies only to those who want to use additional threads to improve performance in their application. We also include a discussion of SwingWorker — a handy class used by many of our demos to offload time-consuming tasks.


Note: Although this section talks about Swing, the same issues apply to all Components. Specifically, AWT components are not guaranteed to be thread safe.

The Event-Dispatching Thread

Swing event-handling and painting code executes in a single thread, called the event-dispatching thread. This ensures that each event handler finishes executing before the next one executes and that painting isn't interrupted by events. To avoid the possibility of deadlock, you must take extreme care that Swing components and models are created, modified, and queried only from the event-dispatching thread.

Note: We used to say that you could create the GUI on the main thread as long as you didn't modify components that had already been realized. [PENDING: The following red text belongs in a footnote.] Realized means that the component has been painted onscreen, or is ready to be painted. The methods setVisible(true) and pack cause a window to be realized, which in turn causes the components it contains to be realized. While this worked for most applications, in certain situations it could cause problems. Out of all the demos in the Swing Tutorial, we encountered a problem only in ComponentEventDemo. In that case, sometimes when you launched the demo, it would not come up because it would deadlock when updating the text area if the text area had not yet been realized, while other times it would come up without incident.

To avoid the possibility of thread problems, we recommend that you use invokeLater to create the GUI on the event-dispatching thread for all new applications. If you have old programs that are working fine they are probably OK; however you might want to convert them when it's convenient to do so.


You have probably noticed that most of the tutorial's demos use a standardized main method that calls the SwingUtilities method invokeLater to ensure that the GUI is created on the event-dispatching thread. Here is an example of the main method from the FocusConceptsDemo example. We have also included the source for createAndShowGUI — a private, static method called by each main method where the creation of the GUI is handled.

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event-dispatching thread.
 */
private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);

    //Create and set up the window.
    frame = new JFrame("FocusConceptsDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JComponent newContentPane = new FocusConceptsDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

Using the invokeLater Method

You can call invokeLater from any thread to request the event-dispatching thread to run certain code. You must put this code in the run method of a Runnable object and specify the Runnable object as the argument to invokeLater. The invokeLater method returns immediately, without waiting for the event-dispatching thread to execute the code. Here's an example of using invokeLater:

Runnable updateAComponent = new Runnable() {
    public void run() { component.doSomething(); }
};
SwingUtilities.invokeLater(updateAComponent);

Using the invokeAndWait Method

The invokeAndWait method is just like invokeLater, except that invokeAndWait doesn't return until the event-dispatching thread has executed the specified code. Whenever possible, you should use invokeLater instead of invokeAndWait — it is very easy to cause a deadlock using invokeAndWait. If you use invokeAndWait, make sure that the thread that calls invokeAndWait does not hold any locks that other threads might need while the call is occurring.

Here's an example of using invokeAndWait:

void showHelloThereDialog() throws Exception {
    Runnable showModalDialog = new Runnable() {
        public void run() {
            JOptionPane.showMessageDialog(myMainFrame,
                                          "Hello There");
        }
    };
    SwingUtilities.invokeAndWait(showModalDialog);
}

Similarly, a thread that needs access to GUI state, such as the contents of a pair of text fields, might have the following code:

void printTextField() throws Exception {
    final String[] myStrings = new String[2];

    Runnable getTextFieldText = new Runnable() {
        public void run() {
            myStrings[0] = textField0.getText();
            myStrings[1] = textField1.getText();
        }
    };
    SwingUtilities.invokeAndWait(getTextFieldText);

    System.out.println(myStrings[0] + " " + myStrings[1]);
}

Using Threads to Improve Performance

When properly used, threads can be a powerful tool. However, you must proceed with caution when using threads in a Swing program. Despite the dangers, threads can be invaluable. You can use them to improve your program's perceived performance. And sometimes threads can simplify a program's code or architecture. Here are some typical situations where threads are used:

If you need to create a thread, you can avoid some common pitfalls by implementing the thread with a utility class such as SwingWorker or one of the Timer classes. A SwingWorker object creates a thread to execute a time-consuming operation. After the operation is finished, SwingWorker gives you the option of executing some additional code in the event-dispatching thread. Timers are useful for performing a task either repeatedly or after a specified delay. If you need to implement your own threads, you can find information on doing so in Threads: Doing Two or More Tasks At Once (in the Creating a GUI with JFC/Swing trail).

You can use several techniques to make multi-threaded Swing programs work well:

For information and examples of using timers, see How to Use Swing Timers.

Using the SwingWorker Class


Note:  The implementation of the SwingWorker (in a .java source file) class has been updated twice, most recently in February 2000. The first update (in January 1999) allowed programs to safely interrupt the worker thread. The most recent update (called "SwingWorker 3") was to fix a subtle threading bug that could cause a NullPointerException.
The SwingWorker class is implemented in SwingWorker.java, which is not in the Swing release. To use the SwingWorker class, you first create a subclass of it. The subclass must implement the construct method so that it contains the code to perform your lengthy operation. When you instantiate your SwingWorker subclass, the SwingWorker creates a thread but does not (as of SwingWorker 3) start it. You then invoke start on your SwingWorker object to start the thread, which then calls your construct method.

Here is an example of using a SwingWorker to move a time-consuming task from an action event listener into a background thread, so that the GUI remains responsive.

//OLD CODE:
public void actionPerformed(ActionEvent e) {
    ...
    //...code that might take a while to execute is here...
    ...
}

//BETTER CODE:
public void actionPerformed(ActionEvent e) {
    ...
    final SwingWorker worker = new SwingWorker() {
        public Object construct() {
            //...code that might take a while to execute is here...
            return someValue;
        }
    };
    worker.start();  //required for SwingWorker 3
    ...
}

The value that construct returns can be any object. If you need to get the value, you can do so by invoking the get method on your SwingWorker object. Be careful about using get. Because it blocks, it can cause deadlock. If necessary, you can interrupt the thread (causing get to return) by invoking interrupt on the SwingWorker.

If you need to update the GUI when the time-consuming operation completes, you can do so either by using get (which is dangerous, as we noted) or by overriding the finished method in your SwingWorker subclass. The finished method runs after the construct method returns. Because the finished method executes in the event-dispatching thread, you can safely use it to update Swing components. Of course, you shouldn't put time-consuming operations in your finished implementation.

The following example of implementing finished is taken from IconDemoApplet.java (in a .java source file). For a full discussion of this applet, including how it improves perceived performance by using background threads to load images, see How to Use Icons.

public void actionPerformed(ActionEvent e) {
    ...
    if (icon == null) {     //haven't viewed this photo before
        loadImage(imagedir + pic.filename, current);
    } else {
        updatePhotograph(current, pic);
    }
}
...
//Load an image in a separate thread.
private void loadImage(final String imagePath, final int index) {
    final SwingWorker worker = new SwingWorker() {
        ImageIcon icon = null;

        public Object construct() {
            icon = new ImageIcon(getURL(imagePath));
            return icon; //return value not used by this program
        }

        //Runs on the event-dispatching thread.
        public void finished() {
            Photo pic = (Photo)pictures.elementAt(index);
            pic.setIcon(icon);
            if (index == current)
                updatePhotograph(index, pic);
        }
    };
    worker.start(); 
}

For more examples of using SwingWorker, go to How to Monitor Progress. Also, TumbleItem.java (in a .java source file), which is discussed in How to Make Applets, uses both a SwingWorker and a Timer.

For more information about Swing thread issues, see the article index in The Swing Connection.
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.