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
2009-11-12 21:52:56
Yeah but wrapping a single method call in a new runnable seems quite cumbersome, doesn't it?
karel_evzen
2009-11-12 21:55:10
cumbersome or not, that's what you have to do if you need to do gui work from another thread
nos
2009-11-12 21:56:03
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
2009-11-12 22:14:28
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
2009-11-12 23:18:18
@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
2009-11-13 01:18:00
+2
A:
No, Swing is not thread safe. Use something like
Runnable doWorkRunnable = new Runnable() {
public void run() { myFrame.dispose(); }
};
SwingUtilities.invokeLater(doWorkRunnable);
nos
2009-11-12 21:55:22