• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Memory leak by "closing" JFrame?

 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Author
Posts: 986
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 502
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic