• Post Reply Bookmark Topic Watch Topic
  • New Topic

Memory leak by "closing" JFrame?  RSS feed

 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose my GUI application opens a second JFrame (perhaps allowing the user to edit data) and then closes that frame, although the application itself keeps running.

Now, I can "close" that second frame by setting visible to false. But if that's all I do, isn't this a memory leak?

It seems to me that I should create a reference to that second frame in my main application, and then as part of closing the second frame, set that reference to null. This should make the "invisible" frame (and any other objects it contains or references) eligible for garbage collection.

So here's my question: Is my reasoning correct? And is there a standard way to do this?
 
Brian Cole
Author
Ranch Hand
Posts: 936
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the javadocs for JFrame.dispose() [which is inherited
from Window] and JFrame.setsetDefaultCloseOperation(DISPOSE_ON_CLOSE).
They free up a lot of memory, but not 100%.

But if we're only talking about one other JFrame and the user might
want to display it again, I'm not sure I'd even worry about dispose().
It's not really a leak unless you're instantiating a new JFrame each
time, as opposed to re-using the same JFrame.
 
Alejandro Barrero
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dispose() does the job. However, you create memory leaks if the second frame has a reference to the first frame. Swing components should never have references to other components.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian and Alejandro: Thanks for the replies. I think dispose will do what I was looking for, but you've both given me other things to think about too. This is my first "non-trivial" Swing application, and I can see I'll need to be very careful in thinking this through.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!