views:

136

answers:

2

Is it safe to call the dispose() method of a JFrame from a different thread (not the EDT)?

+3  A: 

No. It may work or it may cause problems. Just wrap the method in a SwingUtilities.invokeLater(...) and don't worry about it.

camickr
Yeah but wrapping a single method call in a new runnable seems quite cumbersome, doesn't it?
karel_evzen
cumbersome or not, that's what you have to do if you need to do gui work from another thread
nos
It seems unlikely that calling the method is the only thing which is being done. There's probably other code that is being run in a non-thread safe manner. (Anyway, real h4x0rz would use `java.beans.EventHandler`.)
Tom Hawtin - tackline
As a matter of fact there is more potentialy dangerous code running there but is all invoked using SwingUtilities. This dispose method is called from a different method of the class and I was just wondering if you need to wrap the dispose method too, as it is only "freeing" resources, not manipulating with anything else. But I guess disposing is still a manipulation and has to be executed withing the main thread too. :)
karel_evzen
@Tom Hawtin - I'm guess I'm not a real H4x0r then. I prefer compile time safety in my applications. I guess that comes from learning the hard way. Reflection is "cool", but it also a sure-fire way to make your application break easily.
Nemi
+2  A: 

No, Swing is not thread safe. Use something like

Runnable doWorkRunnable = new Runnable() {
    public void run() { myFrame.dispose(); }
};
SwingUtilities.invokeLater(doWorkRunnable);
nos