Event dispatching thread: Difference between revisions

Content deleted Content added
swt, message loop, responsiveness issue
various methods to supply the code for execution by EDT, re-entrant message loop
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 [[.NETStandard FrameworkWidget Toolkit|SWT]], [[SWT.NET Framework]] and [[Android (operating system)|Android]].
 
 
== Message Loop for serializing GUI accesses ==
== Swing and thread safety ==
 
A software application normally consists of multiple threads and a single [[GUI]], which is a complex data structure. ToThis synchronizemeans accessGUI tois thea shared data structure, aand simplesome approachsynchronization is used:needed likewiseto mostensure ofthat theonly GUIone frameworks,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 onlyand fromthese 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
<ref>{{cite web
| url=http://weblogs.java.net/blog/alexfromsun/archive/2005/11/debugging_swing_1.html
| title=Debugging Swing - is it really difficult?
Line 19 ⟶ 18:
| 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>http://www.pushing-pixels.org/?p=368</ref> to prevent such a coding mistake. fromAccess occurringto 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 sumbitted 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.
== 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.
 
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.
 
===Submitting Executinguser code into the event dispatching thread =EDT==
 
There are various solutions for submitting code to the EDT and performing lengthy tasks without blocking the loop.
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:
 
===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 invisible GUI component, whose listeners are register 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 havepass some code to be executed in the event dispatching thread by definingmeans the code in aof {{Javadoc:SE|javajavax/langswing|RunnableSwingUtilities}} objecthelper andclasses pass it to the(or {{Javadoc:SE|javaxjava/swingawt|SwingUtilitiesEventQueue}} helperif classyou orare todoing the[[AWT]]). The submitted code must be wrapped with a {{Javadoc:SE|java/awtlang|EventQueueRunnable}} object. Two methods of these classes allow:
* synchronous code execution ({{Javadoc:SE|member=invokeAndWait(Runnable)|javax/swing|SwingUtilities|invokeAndWait(java.lang.Runnable)}} or {{Javadoc:SE|member=invokeAndWait(Runnable)|java/awt|EventQueue|invokeAndWait(java.lang.Runnable)}})
* and asynchronous code execution ({{Javadoc:SE|member=invokeLater(Runnable)|javax/swing|SwingUtilities|invokeLater(java.lang.Runnable)}} or {{Javadoc:SE|member=invokeLater(Runnable)|java/awt|EventQueue|invokeLater(java.lang.Runnable)}})
Line 35 ⟶ 47:
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 fastquick as possible to prevent freezing. They are normally usedintended to deliver the result of a lengthy computation to the GUI (user).
 
=== Worker design pattern ===
Line 74 ⟶ 86:
 
===Modal Execution===
SwingWorker is normally created for a lengthy tasks by EDT while handling callback (Listener) events. Spawning a worker thread, EDT completesproceeds processinghandling of thecurrent message bywithout immediatelywaiting returningthe fromworker theto callbackcomplete. The open source [http://foxtrotstackoverflow.sourceforge.netcom/docsquestions/worker.php3028842/how-can-swing-dialogs-even-work Foxtrot] project emulates the Swing message loop pumping to provide the "synchronous" execution mechanismOften, whichthis proceedsis onlynot afterdesirable.] the worker completes the task.
 
Often, your EDT handles a GUI component action, which demands the user to make a choice by 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 blocking the EDT executing the current message. The miracle is achieved through entering another message loop, which dispatches the messages as per normal until "modal dialog done" message arrives.
 
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.
 
<source lang="java">
Line 103 ⟶ 119:
});
</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
* <code>System.Windows.Forms.Timer</code> - [[.NET Framework]]
* <code>flash.utils.Timer</code> - [[Adobe Flash]]
 
== See also ==