What exactly is the "Event Dispatch" thread (aka "AWT" Thread)?

Scott Stanchfield

When you run a GUI applet or application, the code in your main() method creates a GUI and sets up event handling. When you call setVisible(true) for your Frame, Window, Dialog, or when the browser displays the Applet, the user must be able to interact with the GUI.

The problem is that your main() method may not end at that point. It could be busy doing some other task, such as computing PI to 40,000 decimal places. If the user had to wait for the main() method to finish before they could interact with the GUI, they could end up quite unhappy.

So the AWT library implements its own thread to watch GUI interaction. This thread is essentially a little loop that checks the system event queue for mouse clicks, key presses and other system-level events. (You can also put your own events in the system queue, but that's another story...).

The AWT thread (aka the "Event Dispatch" thread) grabs a system event off the queue and determines what to do with it. If it looks like a click on top of a component, it calls the mouse click processing handler for that component. That component, in turn, could fire other events. For example, if you click on a JButton, the AWT thread passes the mouse click to the JButton, which interprets it as a "button press", and fires its own actionPerformed event. Anyone listening will have their actionPerformed method called.

The AWT thread also handles repainting of your GUI. Anytime you call repaint(), a "refresh" request is placed in the event queue. Whenever the AWT thread sees a "refresh" request, if examines the GUI for damaged areas or components marked invalid (ie, the text has changed on a Label), then calls the appropriate methods to layout the GUI and paint any components that require painting.

Note: The AWT "thread" may in fact be implemented by multiple threads under some runtime environments. These threads coordinate effort to watch for mouse clicks, keypresses, repaint requests, etc. As far as you're concerned you can treat this all as one "AWT thread".

AWT components are threadsafe, in that if you call a Label's setText() method, it synchronizes such that the displayed text cannot appear with a partially old value and partially new value. However, Swing components, are generally not threadsafe. Because of this, you must make sure that any changes to Swing components that might affect their display are done through the AWT event thread. If the same thread both updates and displays a component, you are guaranteed that the display is consistent.

You can use SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait() to defer processing to the AWT thread.