Event dispatching thread: Difference between revisions

Content deleted Content added
m References: ref cols
swt, message loop, responsiveness issue
Line 1:
The '''event dispatching thread''' (EDT) is a background [[Thread (computer science)|thread]] used in [[Java (programming language)|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 [[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 [[.NET Framework]], [[SWT]] and [[Android (operating system)|Android]].
 
 
== Swing and thread safety ==
 
MostA 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, [[Abstract Window Toolkit|AWT]] and [[Swing (Java)|Swing]] object methods are notexpose [[Thread safety|thread safeunsafe]]: invokingmethods themto fromcreate multipleand threadsaccess risksthe threadGUI interferencecomponents oronly memoryfrom consistencya errorssingle, Event Dispatching thread.<ref>{{cite web
| url=http://download.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
| title=The Event Dispatch Thread
Line 13 ⟶ 14:
| publisher=[http://www.java.net/blogs/alexfromsun/ Alexander Potochkin]
| accessdate=2011-10-02}}
</ref><ref>{{cite web
To avoid these problems, Swing standards state that all [[Graphical user interface|user interface]] components should be created '''and''' accessed '''only''' from the AWT event dispatch thread.<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>
ASince popularprogrammers often miss this requirement, third-party [[Pluggable look and feel|Look and Feel]]s, namedlike [http://java.net/projects/substance/ Substance] goesgo as far as to refuse to instantiate any Swing component when not running within the Event Dispatch Thread,<ref>http://www.pushing-pixels.org/?p=368</ref> to prevent such a coding mistake from occurring.
 
== Message Loop ==
== Executing code in the event dispatching thread ==
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 {{Javadoc:SE|java/lang|Runnable}} object and pass it to the {{Javadoc:SE|javax/swing|SwingUtilities}} helper class or to the {{Javadoc:SE|java/awt|EventQueue}}. Two methods of these classes allow:
Line 30 ⟶ 35:
The method <code>invokeAndWait()</code> should never be called from the event dispatching thread&mdash;it will throw an [[Exception handling|exception]]. The method {{Javadoc:SE|javax/swing|SwingUtilities|isEventDispatchThread()}} or {{Javadoc:SE|java/awt|EventQueue|isDispatchThread()}} 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 fast as possible to prevent freezing. They are normally used to deliver the result of a lengthy computation to the user.
== Worker design pattern ==
Another solution for executing code in the event dispatching thread is using the ''[[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. The open source project [http://foxtrot.sourceforge.net/ Foxtrot] provides another synchronous execution solution similar to <code>SwingWorker</code>.
 
===Samples Worker design pattern ===
AnotherBoth solutionexecution forof executinga codetask in theanother eventthread dispatchingand threadpresenting isthe usingresults 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. TheSwingWorker openis sourcenormally projectinvoked [http://foxtrot.sourceforge.net/from Foxtrot]EDT-executed providesevent anotherListener synchronousto executionperform solutiona similarlengthy task in order not to <code>SwingWorker</code>block the EDT.
 
====Samples====
<source lang="java">
SwingWorker<Document, Void> worker = new SwingWorker<Document, Void>() {
Line 61 ⟶ 68:
</source>
 
====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 Timer 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 [http://foxtrot.sourceforge.net/docs/worker.php Foxtrot] project emulates the Swing message loop pumping to provide the "synchronous" execution mechanism, which proceeds only after the worker completes the task.
You can also run the code in the event dispatching thread using <code>javax.swing.Timer</code>.
 
<source 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();
}
});
</source>
 
=== Timer ===
You can also run the code in the event dispatching thread using <code>javax.swing.Timer</code> as if you register a simple GUI component Listener to be called at specific time(s).
 
Equivalents