Event dispatching thread

The event dispatching thread (EDT) is a background thread used in 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 browsers, or web servers.

The 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 visible user interface components. Updating visible components from other threads is the source of many common bugs in Java programs that use Swing.[1] The event dispatching thread is called the primordial worker in Adobe Flash and the UI thread in SWT, .NET Framework and Android.

Message Loop for serializing GUI accesses

A software application normally consists of multiple threads and a single GUI data structure. This means GUI is a shared data structure and some synchronization is needed to ensure that only one thread accesses it at a time. Though AWT and Swing expose the (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.[2][3][4] Since programmers often miss this requirement, third-party Look and Feels, like Substance go as far as to refuse to instantiate any Swing component when not running within the Event Dispatch Thread,[5] 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, javax.swing.Timer is used. It can be considered as invisible GUI component, whose listeners are register to fire at specific time(s).

Equivalents

Requests from other threads

Other application threads can pass some code to be executed in the event dispatching thread by means of SwingUtilities helper classes (or EventQueue if you are doing AWT). The submitted code must be wrapped with a Runnable object. Two methods of these classes allow:

from the event dispatching thread.

The method invokeAndWait() should never be called from the event dispatching threadit will throw an exception. The method SwingUtilities.isEventDispatchThread() or EventQueue.isDispatchThread() can be called to determine if the current thread is the event dispatching thread.

The code supplied by means of the invokeLater and invokeAndWait 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 worker design pattern. The javax.swing.SwingWorker 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

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();

If you use Groovy and groovy.swing.SwingBuilder, you can use doLater(), doOutside(), and edt(). Then you can write it more simple like this.

doOutside {
    def doc = loadXML() // heavy task
    edt { display(doc) }
}

Equivalents

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. 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 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.

  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();
	 }
  });

Since Java 1.7, Java provides standard solution for custom secondary message loops by exposing createSecondaryLoop() in system EventQueue().

See also

References

  1. This problem is not specific to Java Swing. There is the same issue in most Widget toolkits, as for example Windows Forms, where the BackgroundWorker class performs the same purpose as SwingWorker in Java.
  2. "The Event Dispatch Thread". Sun Microsystems. Retrieved 2011-10-02.
  3. "Debugging Swing - is it really difficult?". Alexander Potochkin. Retrieved 2011-10-02.
  4. "Initial Threads". Sun Microsystems. Retrieved 2011-10-02.
  5. http://www.pushing-pixels.org/?p=368

External links

This article is issued from Wikipedia - version of the Sunday, June 28, 2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.