Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should you have to dispose() a java.awt.Window that goes out of scope?

One of the memory leaks I've discovered in our application is the java.awt.Window.allWindows private static field, which keeps track of every Window instantiated. We have dialog boxes that are created, used, and then forgotten, and the expectation was that these would go away and be garbage collected. This private field keeps them in scope, indefinitely, until the dispose() method is called on them. And by definition, we can't do that when they've gone out of scope.

I don't understand why this is designed this way. It seems contrary to the spirit of garbage collection to have to explicitly let the system know when I'm done with a Window object. Obviously I'm done with it, as it is out of scope.

I understand what the dispose() method is doing: getting rid of system peer objects. I do understand that this is outside of Java and that you need some way to do that and that Swing shouldn't just lose track of those objects, or else it would have a memory leak. But what is accomplished by keeping a reference to my Window around forever, when I am never going to use it again?

Can someone explain why this is necessary?

like image 929
skiphoppy Avatar asked Sep 10 '09 19:09

skiphoppy


1 Answers

I hate to say it, but that's just how a GUI works.

Windows are non-blocking. Meaning that once you create one in code, your code continues to execute.

This means that your Window probably goes out of scope immediately after creation, unless you explicitly stored a reference to it somewhere else. The Window is still on screen at this point.

This also means you need some other way to get rid of it when you're done with it. Enter the Window dispose() method, which can be called from within one of the Window's listeners.

like image 84
Powerlord Avatar answered Oct 10 '22 05:10

Powerlord