Why is it important to use invokeLater?
Asked Answered
R

4

3

I recently found an example code:

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

The createAndShowGUI() method opens a user interface window. Then I tried to trim the code as the following:

public static void main(String[] args) {
    createAndShowGUI();
}

Both versions work equally well. What is the difference?

Runstadler answered 3/10, 2013 at 19:2 Comment(2)
It works equally well, most of the time, but occasionally your GUI thread and the thread updating the GUI will cause strange and unreproducible behaviour. This is the problem with testing multi-threaded code, You can run it fine for days and change something minor and suddenly it shows up often.Bedsore
Possible duplicate of #6568370Fredela
E
10

99% of the time either code will work.

However, Swing was designed such that all updates to Swing components should be done on the Event Dispatch Thread (EDT). Read the Swing tutorial on Concurrency for more information.

The problem is the 1% of the time when it might not work. You don't want to waste time trying to debug random problems.

Everyman answered 3/10, 2013 at 19:4 Comment(0)
J
4

SwingUtilities.invokeLater ensures that the code executes on the Event Dispatch Thread (EDT). Swing is single-threaded, all component instantiation and display should happen on the EDT. Things might seem to work otherwise, but you'll possibly run into issues.

Juarez answered 3/10, 2013 at 19:5 Comment(0)
I
3

Swing has single threaded Event Loop based design and is not thread safe, with only thread safe part being a set of invokeXXX() methods used to transfer control to the Swing event loop.

Your "broken" code works just fine because nothing else is trying to touch the same part of Swing data structures from within the Event Loop at the same time.

Ingalls answered 3/10, 2013 at 19:7 Comment(0)
T
3

The "main" thread started by the JVM is not the Event Dispatch Thread.

from The Event Dispatch Thread

Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

Tepid answered 3/10, 2013 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.