Technology Inside Out!

Index ¦ Archives ¦ Atom ¦ RSS

Understanding Event Dispatching Thread in Java

Swing provides a rich toolkit of GUI components which can be used to create powerful User Interface. Sometimes, we don’t get expected results when we are working on complex GUI & try to update GUI of that running application. From running application we mean that we have a Swing application running and we update something in the app while it is running. There are some rules (as per API documentation), which if followed correctly, can lead to expected results in a GUI application.

A normal swing application is started within the event dispatching thread in this way :

public static void main(String[]args)
{
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            new ConstructorOfClass();
        }   
    });
}

According to Oracle Documentation, when a Swing Application starts, two threads start running : Main Thread  and Event Dispatching Thread (EDT) . The ED thread consists of the code related to GUI of the application. The main thread just executes the logic of the application, but whenever GUI needs to be updated, it must be passed to the EDT. The usual way of calling code inside EDT is :

SwingUtilities.invokeLater(new Runnable()
{
    public void run()
    {
/*       EDT code here like updating label, button
         or some other work related to GUI updation
*/
    }
});

So if we are calculating something and after that we need to update some component in GUI, we will write the GUI updation code inside the run method as shown above. SwingUtilities's invokeLater method takes Runnable objects and executes them one by one on a single thread (EDT) so that their is no ambiguity related to updation of GUI. In contrast to this approach, if we write the GUI updation code in some other thread (or even main thread), we may not get expected results.This is so because many Swing methods are not thread-safe.

Thread Safety : Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized.This is given in API documentation that all GUI updation should be strictly done in only one thread called the Event Dispatching Thread.

© The Geeky Way. Built using Pelican. Theme by Giulio Fidente on github.

Disclaimer Privacy policy