javaswingswingutilities

How can I make SwingUtilities.invokeLater execute tasks faster?


I use SwingUtilities.invokeLater to update the UI. Sometimes tasks are executed almost at as soon as invokeLater is called, but sometimes it takes few seconds for it, that I would like to avoid. Are there any settings that can help me with this?

I know that tasks are executed in a AWT event-dispatching thread, but is there a way to forcefully clear the queue of it (probably not a great idea), or somehow add another AWT thread to work in parallel, or any other solution that may help with executing tasks faster?

Is it even possible to influence this things, or all I can do is just create some daemon threads by myself? I'd like to avoid that.


Solution

  • There are things that have to be done on the event handler thread. Swing isn't thread-safe, and not following that rule makes WEIRD things happen.

    As there is only one such thread (and you can't create additional ones), make sure it's used only for things where it's necessary. So, don't do complex computations on that thread. Check your paintComponent() methods, invokeLater() calls etc. for time-consuming parts.

    Either optimize their performance or refactor them to some other "worker" thread. You can have as many worker threads as you like, as long as they stay away from calling Swing methods. The fact that you are asking about invokeLater() implies that you're already using at least one thread besides the event handler.

    A decent profiler tool will be helpful in that process.