What does SwingUtilities.invokeLater do?

user633784 picture user633784 · Jul 4, 2011 · Viewed 58.5k times · Source

What does SwingUtilities.invokeLater do? Is it just delaying the execution of a block of codes inside its run method? What is the difference between calling an action within the invokeLater function or simply calling it at the end of the thread we want to be executed? Can anyone help me with what really does the invokeLater function do?

Answer

Maurice Naftalin picture Maurice Naftalin · Jul 4, 2011

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.