Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Event dispatching thread
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
The '''event dispatching thread''' (EDT) is a background [[Thread (computing)|thread]] used in [[Java (programming language)|Java]] to process events from the [[Abstract Window Toolkit]] (AWT) [[graphical user interface]] [[event queue]]. It is an example of the generic concept of [[event-driven programming]], that is popular in many other contexts than Java, for example, [[web browser]]s, or [[web server]]s. The events are primarily update events that cause user interface [[Software componentry|components]] to redraw themselves, or input events from [[input device]]s such as the mouse or keyboard. The AWT uses a single-threaded painting [[Model (abstract)|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 [[Software bug|bugs]] in Java [[Computer program|programs]] that use [[Swing (Java)|Swing]].<ref>This problem is not specific to Java [[Swing (Java)|Swing]]. There is the same issue in most [[Widget toolkit]]s, as for example [[Windows Forms]], where the [[BackgroundWorker]] class performs the same purpose as [[SwingWorker]] in Java.</ref> The event dispatching thread is called the '''primordial worker''' in [[Adobe Flash]] and the '''UI thread''' in [[Standard Widget Toolkit|SWT]], [[.NET Framework]] and [[Android (operating system)|Android]]. == Message loop for serializing GUI accesses == A software application normally consists of multiple threads and a single GIT data structure. This means GIT is a shared data structure and some synchronization is needed to ensure that only one thread accesses it at a time. Though [[Abstract Window Toolkit|AWT]] and [[Swing (Java)|Swing]] expose the ([[Thread safety|thread unsafe]]) methods to create and access the GUI components and these methods are visible to all application threads, likewise in other GUI frameworks, only a single, Event Dispatching thread has the right to execute these methods.<ref>{{cite web | url=http://download.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html | title=The Event Dispatch Thread | publisher=[[Sun Microsystems]] | accessdate=2011-10-02}}</ref><ref>{{cite web | url=http://weblogs.java.net/blog/alexfromsun/archive/2005/11/debugging_swing_1.html | title=Debugging Swing - is it really difficult? | publisher=Alexander Potochkin | accessdate=2011-10-02 | archive-url=https://web.archive.org/web/20110805132240/http://weblogs.java.net/blog/alexfromsun/archive/2005/11/debugging_swing_1.html | archive-date=2011-08-05 | url-status=dead }}</ref><ref>{{cite web | url=http://download.oracle.com/javase/tutorial/uiswing/concurrency/initial.html | title=Initial Threads | publisher=[[Sun Microsystems]] | accessdate=2011-10-02}}</ref> Since programmers often miss this requirement, third-party [[Pluggable look and feel|Look and Feel]]s, like [http://java.net/projects/substance/ Substance] go as far as to refuse to instantiate any Swing component when not running within the Event Dispatch Thread,<ref>{{Cite web|url=http://www.pushing-pixels.org/?p=368|title=Stricter checks on EDT violations in Substance Β· Pushing Pixels}}</ref> to prevent such a coding mistake. Access to the GUI is serialized and other threads may submit some code to be executed in the EDT through a '''EDT message queue'''. That is, likewise in other GUI frameworks, the Event Dispatching Thread spends its life pumping messages: it maintains a message queue of actions to be performed over GUI. These requests are submitted to the queue by system and any application thread. EDT consumes them one after another and responds by updating the GUI components. The messages may be well-known actions or involve callbacks, the references to user-methods that must be executed by means of EDT. 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. ==Submitting user code to the EDT== There are various solutions for submitting code to the EDT and performing lengthy tasks without blocking the loop. ===Component event handlers (listeners)=== GUI components support the lists of callbacks, called Listeners, which are typically populated when the components are created. EDT executes the listeners when user excitates the components somehow (button is clicked, mouse is moved, item is selected, focus is lost, component resized and so on.) === Timer === For short tasks that must access/modify GUI periodically or at specific time, <code>javax.swing.Timer</code> is used. It can be considered as an invisible GUI component, whose listeners are registered to fire at specific time(s). Equivalents * <code>System.Windows.Forms.Timer</code> - [[.NET Framework]] * <code>flash.utils.Timer</code> - [[Adobe Flash]] === Requests from other threads === Other application threads can pass some code to be executed in the event dispatching thread by means of {{Javadoc:SE|javax/swing|SwingUtilities|module=java.desktop}} helper classes (or {{Javadoc:SE|java/awt|EventQueue|module=java.desktop}} if you are doing [[Abstract Window Toolkit|AWT]]). The submitted code must be wrapped with a {{Javadoc:SE|java/lang|Runnable}} object. Two methods of these classes allow: * synchronous code execution ({{Javadoc:SE|member=invokeAndWait(Runnable)|javax/swing|SwingUtilities|invokeAndWait(java.lang.Runnable)|module=java.desktop}} or {{Javadoc:SE|member=invokeAndWait(Runnable)|java/awt|EventQueue|invokeAndWait(java.lang.Runnable)|module=java.desktop}}) * and asynchronous code execution ({{Javadoc:SE|member=invokeLater(Runnable)|javax/swing|SwingUtilities|invokeLater(java.lang.Runnable)|module=java.desktop}} or {{Javadoc:SE|member=invokeLater(Runnable)|java/awt|EventQueue|invokeLater(java.lang.Runnable)|module=java.desktop}}) from the event dispatching thread. The method <code>invokeAndWait()</code> should never be called from the event dispatching thread—it will throw an [[Exception handling|exception]]. The method {{Javadoc:SE|javax/swing|SwingUtilities|isEventDispatchThread()|module=java.desktop}} or {{Javadoc:SE|java/awt|EventQueue|isDispatchThread()|module=java.desktop}} can be called to determine if the current thread is the event dispatching thread. The code supplied by means of the <code>invokeLater</code> and <code>invokeAndWait</code> to the EDT must be as quick as possible to prevent freezing. They are normally intended to deliver the result of a lengthy computation to the GUI (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 ''[[SwingWorker|worker design pattern]]''. The <code>[[SwingWorker|javax.swing.SwingWorker]]</code> 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==== <syntaxhighlight lang="java"> 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(); </syntaxhighlight> If you use [[Groovy (programming language)|Groovy]] and <code>groovy.swing.SwingBuilder</code>, you can use <code>doLater()</code>, <code>doOutside()</code>, and <code>edt()</code>. Then you can write it more simply like this: <syntaxhighlight lang="groovy"> doOutside { def doc = loadXML() // heavy task edt { display(doc) } } </syntaxhighlight> ====Equivalents==== * <code>System.ComponentModel.BackgroundWorker</code> - [[.NET Framework]] * <code>flash.system.Worker</code> - [[Adobe Flash]] * <code>android.os.AsyncTask</code> - [[Android (operating system)|Android]] ===Modal execution=== SwingWorker is normally created for a lengthy tasks by EDT while handling callback (Listener) events. Spawning a worker thread, EDT proceeds handling current message without waiting the worker to complete. [https://stackoverflow.com/questions/3028842/how-can-swing-dialogs-even-work Often, this is not desirable.] Often, your EDT handles a GUI component action, which demands the user to make a choice by means of another dialog, like JFileChooser, which pops up, stays responsive while user picks its option and action proceeds with selected file only after "OK" button is pressed. You see, this takes time (user responds in matter of seconds) and you need a responsive GUI (the messages are still pumped in EDT) during all this time while EDT is blocking (it does not handle newer, e.g. JFileChooser, messages in the queue before the dialog is closed and current component action is finished). The vicious cycle is broken through EDT entering a new message loop, which dispatches the messages as per normal until "modal dialog is over" arrives and normal message processing resumes from the blocked position in the component action. The open source '''[http://foxtrot.sourceforge.net/docs/worker.php Foxtrot]''' project emulates the Swing message loop pumping to provide the "synchronous" execution mechanism for arbitrary user tasks, which proceeds only after the worker completes the task. <syntaxhighlight lang="java"> 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(); } }); </syntaxhighlight> Since Java 1.7, Java provides '''standard''' solution for custom '''secondary message loops''' by exposing ''createSecondaryLoop''() in system ''EventQueue''(). == See also == * [[Abstract Window Toolkit]] (AWT) * [[Swing (Java)]] * [[SwingWorker]] ==References== {{reflist|30em}} == External links == * {{Javadoc:SE|package=javax.swing|javax/swing|module=java.desktop}} (Swing API [[Javadoc]] documentation) * {{Javadoc:SE|package=java.awt|java/awt|module=java.desktop}} (AWT API [[Javadoc]] documentation) * {{Javadoc:SE-guide|swing|Swing API documentation}} * [http://download.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html The Event-Dispatching Thread] * [http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html SwingWorker] description from the Swing tutorial * [http://tech.stolsvik.com/2009/03/awt-swing-event-pumping-and-targeting.html AWT/Swing event handling] article about event pumping, dispatch and processing, and the EDT * [http://foxtrot.sourceforge.net/ Foxtrot project home page] {{DEFAULTSORT:Event Dispatching Thread}} [[Category:JDK components]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite web
(
edit
)
Template:Javadoc:SE
(
edit
)
Template:Javadoc:SE-guide
(
edit
)
Template:Reflist
(
edit
)