What does SwingUtilities.invokeLater do? [duplicate] What does SwingUtilities.invokeLater do? [duplicate] java java

What does SwingUtilities.invokeLater do? [duplicate]


As other answers have said, it executes your Runnable on the AWT event-dispatching thread. But why would you want to do that? Because the Swing data structures aren't thread-safe, so to provide programmers with an easily-achievable way of preventing concurrent access to them, the Swing designers laid down the rule that all code that accesses them must run on the same thread. That happens automatically for event-handling and display maintenance code, but if you've initiated a long-running action - on a new thread, of course - how can you signal its progress or completion? You have to modify a Swing control, and you have to do it from the event-dispatching thread. Hence invokeLater.


It will run the piece of code on the AWT thread. Which lets you modify the GUI from other threads.

From Docs:

Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI.


As already noted, InvokeLater allows you to safely call methods in swing classes when you are not running on the EventQueue to begin with. However, you can simplify your code and your life by accessing other fields and classes only from the EventQueue. They can work with swing and each other without all the hassles of multi-threading. If you have started another thread, use InvokeLater to get back to the EventQueue as quickly as possible and minimize the number of fields that must be synchronized or otherwise guarded.

If you need to make the most of multiple cores you will have to reduce your use of the EventQueue, and you will have to pay a big price in complexity.