Event dispatching thread
The event dispatching thread (EDT) is a background thread used in Java to process events from the Abstract Window Toolkit (AWT) graphical user interface event queue. These events are primarily update events that cause user interface components to redraw themselves, or input events from input devices such as the mouse or keyboard. The AWT uses a single-threaded painting model in which all screen updates must be performed from a single thread. The event dispatching thread is the only valid thread to update the visual state of visible user interface components. Updating visible components from other threads is the source of many common bugs in Java programs that use Swing.[1] The event dispatching thread is called the primordial worker in Adobe Flash and the UI thread in .NET Framework, SWT and Android.
Swing and thread safety
A software application normally consists of multiple threads and a single GUI, which is a complex data structure. To synchronize access to the shared data structure, a simple approach is used: likewise most of the GUI frameworks, AWT and Swing expose thread unsafe methods to create and access the GUI components only from a single, Event Dispatching thread.[2] [3][4] Since programmers often miss this requirement, third-party Look and Feels, like Substance go as far as to refuse to instantiate any Swing component when not running within the Event Dispatch Thread,[5] to prevent such a coding mistake from occurring.
Message Loop
Likewise in other GUI framework, the Event Dispatching Thread spends its life pumping messages: it maintains a message queue from (other threads and system) and responds to them updating the GUI components. The messages may involve callbacks, the references to user-methods that must be executed by means of EDT. Many of the callbacks, called Listeners, are registered when GUI components are created. EDT executes them when button is clicked, mouse is moved, focus is lost, component resized and other user activity in the GUI. The important requirement imposed on all messages is that they must be executed quickly for the GUI to stay responsive. Otherwise, the message loop is blocked and GUI freezing is experienced.
There are various solutions for the lengthy tasks.
Executing code in the event dispatching thread
Other application threads can have code executed in the event dispatching thread by defining the code in a Runnable
object and pass it to the SwingUtilities
helper class or to the EventQueue
. Two methods of these classes allow:
- synchronous code execution (
SwingUtilities.invokeAndWait(Runnable)
orEventQueue.invokeAndWait(Runnable)
) - and asynchronous code execution (
SwingUtilities.invokeLater(Runnable)
orEventQueue.invokeLater(Runnable)
)
from the event dispatching thread.
The method invokeAndWait()
should never be called from the event dispatching thread—it will throw an exception. The method SwingUtilities.isEventDispatchThread()
or EventQueue.isDispatchThread()
can be called to determine if the current thread is the event dispatching thread.
The code supplied by means of the invokeLater
and invokeAndWait
to the EDT must be as fast as possible to prevent freezing. They are normally used to deliver the result of a lengthy computation to the user.
Worker design pattern
Both execution of a task in another thread and presenting the results in the EDT can be combined by means of worker design pattern. The javax.swing.SwingWorker
class, developed by Sun Microsystems, is an implementation of the worker design pattern, and as of Java 6 is part of standard Swing distribution. SwingWorker is normally invoked from EDT-executed event Listener to perform a lengthy task in order not to block the EDT.
Samples
SwingWorker<Document, Void> worker = new SwingWorker<Document, Void>() {
public Document doInBackground() throws IOException {
return loadXML(); // heavy task
}
public void done() {
try {
Document doc = get();
display(doc);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
worker.execute();
If you use Groovy and groovy.swing.SwingBuilder
, you can use doLater()
, doOutside()
, and edt()
. Then you can write it more simple like this.
doOutside {
def doc = loadXML() // heavy task
edt { display(doc) }
}
Equivalents
System.ComponentModel.BackgroundWorker
- .NET Frameworkflash.system.Worker
- Adobe Flashandroid.os.AsyncTask
- Android
Modal Execution
SwingWorker is normally created for a lengthy tasks by EDT while handling callback (Listener) events. Spawning a worker thread, EDT completes processing of the message by immediately returning from the callback. The open source Foxtrot project emulates the Swing message loop pumping to provide the "synchronous" execution mechanism, which proceeds only after the worker completes the task.
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
button.setText("Sleeping...");
String text = null;
try
{
text = (String)Worker.post(new Task()
{
public Object run() throws Exception
{
Thread.sleep(10000);
return "Slept !";
}
});
}
catch (Exception x) ...
button.setText(text);
somethingElse();
}
});
Timer
You can also run the code in the event dispatching thread using javax.swing.Timer
as if you register a simple GUI component Listener to be called at specific time(s).
Equivalents
System.Windows.Forms.Timer
- .NET Frameworkflash.utils.Timer
- Adobe Flash
See also
References
- ^ This problem is not specific to Java Swing. There is the same issue in most Widget toolkits, as for example Windows Forms, where the BackgroundWorker class performs the same purpose as SwingWorker in Java.
- ^ "The Event Dispatch Thread". Sun Microsystems. Retrieved 2011-10-02.
- ^ "Debugging Swing - is it really difficult?". Alexander Potochkin. Retrieved 2011-10-02.
{{cite web}}
: External link in
(help)|publisher=
- ^ "Initial Threads". Sun Microsystems. Retrieved 2011-10-02.
- ^ http://www.pushing-pixels.org/?p=368
External links
javax.swing
(Swing API Javadoc documentation)java.awt
(AWT API Javadoc documentation)- Swing API documentation
- The Event-Dispatching Thread
- SwingWorker description from the Swing tutorial
- AWT/Swing event handling article about event pumping, dispatch and processing, and the EDT
- Foxtrot project home page