How can I make SwingUtilities.invokeLater execute tasks faster?

206 views Asked by At

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.

2

There are 2 answers

0
Ralf Kleberhoff On BEST ANSWER

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.

2
arcy On

Have you tried SwingUtilities.invokeAndWait()? It sounds like you don't want to have the program do other things threaded with the Swing operations, you want them done right now.

Of course this won't actually caused them to be done in any fewer CPU cycles, and if there are things already queued up for the dispatch thread, this doesn't get rid of them or anything.

There are also things like loading up images from files that can either be done synchronously or asynchronously -- if you're trying to eliminate pauses, you might make sure those are being done as you want.