The event dispatching thread (EDT) is a background thread used in Java to process events from the Abstract Windowing 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 user interface components. Updating visual components from other threads is the source of many common bugs in Java programs that use Swing.
Executing code in the EDT
Other application threads can execute code in the event dispatching thread by defining the code in a Runnable
object and pass it to the SwingUtilities
helper class. Two methods of this class allow synchronous (SwingUtilities.invokeAndWait(Runnable)
) and asynchronous (SwingUtilities.invokeLater(Runnable)
) code execution from the EDT. The method invokeAndWait()
should never be called from the event dispatching thread—it will throw an exception. The methodSwingUtilities.isEventDispatchThread()
can be called to determine if the current thread is the event dispatching thread.
Another solution for executing code in the EDT is using the worker design pattern. The SwingWorker
class, developed by Sun Microsystems, is an implementatino of the worker design pattern, but is not a part of standard Swing distribution. The open source project Foxtrot provides another synchronous execution solution similar to SwingWorker
.
See also
External links
javax.swing
(Swing API Javadoc documentation)java.awt
(AWT API [[Javadoc] documentation)- Swing API documentation
- AWT API documentation
- The Event-Dispatching Thread
- SwingWorker class source code
- SwingWorker description from http://java.sun.com tutorial on Swing
- Foxtrot project home page
- Swing multithreading issues article on SwingWiki.org, containing descriptions and workarounds for several problems caused by EDT misuse
- Use worker thread for long operations article on SwingWiki.org, containing code examples for SwingWorker and Foxtrot