javamultithreadingswinginvokelateredt

SwingUtilities InvokeLater- what is considered bad practice?


I've got a question about what would be the correct practice to use the invokeLater method of SwingUtilities.

So to begin, I'd like to confirm that I am understanding it correctly.

From what I understand, changes to the GUI must be done on the EDT, because Swing components aren't thread safe. The invokeLater method takes a Runnable as an argument, and anything contained in that runnable will be run on the EDT. Therefore any calls made to Swing components are put in a kind of queue, which are executed one at a time on the EDT.

With that out of the way, my question then is: what is good practice for using this? From what I can see there are at least two ways to do it:

1) In the main method, place all code, such as GUI creation, Controller creation, and even the Model creation (assuming a MVC type pattern), in a Runnable that is invoked by the invokeLater method. Of course, this is assuming that any long running tasks in the Model would be executed with a SwingWorker.

2) Place GUI creation in a invokeLater, but Controller creation and Model creation in the main method. Then whenever you need to access a Swing component from a Controller, you pop said code in an invokeLater method to place it on the EDT queue.

What one of these two would be considered best practice, or bad practice? And if neither of these two are good, what would be the better way to go about this?

Any info would be hugely appreciated.

Thanks.


Solution

  • SwingWorker isn't special, it's just some wrappers around common scenarios. It will call invokeLater on your behalf so really both cases you present are just instances of the same thing.

    Just make sure you follow these two rules: 1. Don't stall the EDT 2. Perform Swing-related code on the EDT