Event dispatching thread
Event Dispatch Thread
AWT toolkit in Java uses a single-threaded painting model, in which all screen updates must be performed from a single thread (even in multithreaded applications). Event Dispatch Thread is a background thread used to process events from the AWT event queue, and is the only valid thread to update visual components on the screen. Updating visual components from other threads is the source of most common errors in Swing.
In order to use the Event Dispatch Thread from other application threads, you can wrap your code into a Runnable object, and pass it to SwingUtilities helper class. Two methods of this class allow synchronous invokeAndWait(Runnable) and asynchronous (invokeLater(Runnable)) code execution from the EDT. Method invokeAndWait() should never be called from the event dispatch thread - it will throw an Exception in that case. If you are unsure about the current thread, use SwingUtilities.isEventDispatchThread() to check.
Another common solution for executing code in the EDT is using the SwingWorker class. That class was developed by Sun Microsystems, but is not a part of standard Swing distribution.
Opensource project Foxtrot provides a synchronous execution solution similar to SwingWorker.
External links
- SwingWorker class source code
- Foxtrot project home page
- SwingWorker description from java.sun.com tutorial on Swing
- 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