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.
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 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.
There are various solutions for submitting code to the EDT and performing lengthy tasks without blocking the loop.
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.)
For short tasks that must access/modify GUI periodically or at specific time, javax.swing.Timer
is used. It can be considered as an invisible GUI component, whose listeners are registered to fire at specific time(s).
Equivalents
System.Windows.Forms.Timer
- .NET Framework flash.utils.Timer
- Adobe Flash 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:
SwingUtilities.invokeAndWait(Runnable)
or EventQueue.invokeAndWait(Runnable)
) SwingUtilities.invokeLater(Runnable)
or EventQueue.invokeLater(Runnable)
)from the event dispatching thread.
The method invokeAndWait()
should never be called from the event dispatching thread—it 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).
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.
SwingWorker<Document,Void>worker=newSwingWorker<Document,Void>(){publicDocumentdoInBackground()throwsIOException{returnloadXML();// heavy task}publicvoiddone(){try{Documentdoc=get();display(doc);}catch(Exceptionex){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 simply like this:
doOutside{defdoc=loadXML()// heavy taskedt{display(doc)}}
System.ComponentModel.BackgroundWorker
- .NET Framework flash.system.Worker
- Adobe Flash android.os.AsyncTask
- Android 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(newActionListener(){publicvoidactionPerformed(ActionEvente){button.setText("Sleeping...");Stringtext=null;try{text=(String)Worker.post(newTask(){publicObjectrun()throwsException{Thread.sleep(10000);return"Slept !";}});}catch(Exceptionx)...button.setText(text);somethingElse();}});
Since Java 1.7, Java provides standard solution for custom secondary message loops by exposing createSecondaryLoop() in system EventQueue().
Java Platform, Standard Edition is a computing platform for development and deployment of portable code for desktop and server environments. Java SE was formerly known as Java 2 Platform, Standard Edition (J2SE).
In computer programming, event-driven programming is a programming paradigm in which the flow of the program is determined by external events. Typical event can be UI events from mice, keyboards, touchpads and touchscreens, or external sensor inputs, or be programmatically generated from other programs or threads, or network events.
In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.
In computer programming, the word trampoline has a number of meanings, and is generally associated with jump instructions.
Windows Forms (WinForms) is a free and open-source graphical (GUI) class library included as a part of Microsoft .NET, .NET Framework or Mono, providing a platform to write client applications for desktop, laptop, and tablet PCs. While it is seen as a replacement for the earlier and more complex C++ based Microsoft Foundation Class Library, it does not offer a comparable paradigm and only acts as a platform for the user interface tier in a multi-tier solution.
Java Authentication and Authorization Service, or JAAS, pronounced "Jazz", is the Java implementation of the standard Pluggable Authentication Module (PAM) information security framework. JAAS was introduced as an extension library to the Java Platform, Standard Edition 1.3 and was integrated in version 1.4.
SwingWorker is a popular utility class developed by Sun Microsystems for the Swing library of the Java programming language. SwingWorker enables proper use of the event dispatching thread. As of Java 6, SwingWorker is included in the JRE.
In software engineering, inversion of control (IoC) is a design pattern in which custom-written portions of a computer program receive the flow of control from a generic framework. The term "inversion" is historical: a software architecture with this design "inverts" control as compared to procedural programming. In procedural programming, a program's custom code calls reusable libraries to take care of generic tasks, but with inversion of control, it is the framework that calls the custom code.
The Java Media Framework (JMF) is a Java library that enables audio, video and other time-based media to be added to Java applications and applets. This optional package, which can capture, play, stream, and transcode multiple media formats, extends the Java Platform, Standard Edition and allows development of cross-platform multimedia applications.
The message loop is an obligatory section of code in every program that uses a graphical user interface under Microsoft Windows. Windows programs that have a GUI are event-driven. Windows maintains an individual message queue for each thread that has created a window. Usually only the first thread creates windows. Windows places messages into that queue whenever mouse activity occurs on that thread's window, whenever keyboard activity occurs while that window has focus, and at other times. A process can also add messages to its own queue. To accept user input, and for other reasons, each thread with a window must continuously retrieve messages from its queue, and act on them. A programmer makes the process do that by writing a loop that calls GetMessage, and then calls DispatchMessage, and repeats indefinitely. This is the message loop. There usually is a message loop in the main program, which runs on the main thread, and additional message loop in each created modal dialog. Messages for every window of the process pass through its message queue, and are handled by its message loop. A message loop is one kind of event loop.
In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider", then calls the relevant event handler. The event loop is also sometimes referred to as the message dispatcher, message loop, message pump, or run loop.
Layout managers are software components used in widget toolkits which have the ability to lay out graphical control elements by their relative positions without using distance units. It is often more natural to define component layouts in this manner than to define their position in pixels or common distance units, so a number of popular widget toolkits include this ability by default. Widget toolkits that provide this function can generally be classified into two groups:
BD-J, or Blu-ray Disc Java, is a specification supporting Java ME Xlets for advanced content on Blu-ray Disc and the Packaged Media profile of Globally Executable MHP (GEM).
In programming and software design, an event is an action or occurrence recognized by software, often originating asynchronously from the external environment, that may be handled by the software. Computer events can be generated or triggered by the system, by the user, or in other ways. Typically, events are handled synchronously with the program flow; that is, the software may have one or more dedicated places where events are handled, frequently an event loop.
Parallel Extensions was the development name for a managed concurrency library developed by a collaboration between Microsoft Research and the CLR team at Microsoft. The library was released in version 4.0 of the .NET Framework. It is composed of two parts: Parallel LINQ (PLINQ) and Task Parallel Library (TPL). It also consists of a set of coordination data structures (CDS) – sets of data structures used to synchronize and co-ordinate the execution of concurrent tasks.
Model–view–presenter (MVP) is a derivation of the model–view–controller (MVC) architectural pattern, and is used mostly for building user interfaces.
Grand Central Dispatch, is a technology developed by Apple Inc. to optimize application support for systems with multi-core processors and other symmetric multiprocessing systems. It is an implementation of task parallelism based on the thread pool pattern. The fundamental idea is to move the management of the thread pool out of the hands of the developer, and closer to the operating system. The developer injects "work packages" into the pool oblivious of the pool's architecture. This model improves simplicity, portability and performance.
The Abstract Window Toolkit (AWT) is Java's original platform-dependent windowing, graphics, and user-interface widget toolkit, preceding Swing. The AWT is part of the Java Foundation Classes (JFC) — the standard API for providing a graphical user interface (GUI) for a Java program. AWT is also the GUI toolkit for a number of Java ME profiles. For example, Connected Device Configuration profiles require Java runtimes on mobile telephones to support the Abstract Window Toolkit.
JWt is an open-source widget-centric web application framework for the Java programming language developed by Emweb. It has an API that uses established GUI application development patterns. The programming model is component-based and event-driven, similar to Swing.
{{cite web}}
: External link in |publisher=
(help) javax.swing
(Swing API Javadoc documentation) java.awt
(AWT API Javadoc documentation)