1

I have a program with GUI with segment that can be large and contain a lot of objects. One of the features of my program is to "close" that segment and create a new one.

This whole segment is attached to the program by only one JPanel and an ArrayList. If I dispose of/set those two to null there should be no way to access the any of the JPanels childen (one of which are complex object extending GUI components, but also containing a lot of variables).

If I'm correct, all of JPanels childeren will be collected by garbage collector.

However, what happens to the children of the children? I have some "families" that go up to 5-6 "generations". Will they be deleted only upon GC's 5th (or 6th) pass, or will it detect the whole "family" as unacessible and collect it all at once (or upon it's first pass)?

EDIT: Another minor question: Is there a method for swing component that will remove all of it's children?

Angelos Chalaris
  • 5,882
  • 7
  • 44
  • 65
Karlovsky120
  • 5,718
  • 7
  • 30
  • 79
  • 1
    As far as I know the GC will not be picky about removing objects! Dereferenced objects get garbage collected without the gc looking which "generation" they belong to. Which means that if the last three generations are useless objects they will get all garbage collected! – Angelos Chalaris Sep 11 '12 at 20:05
  • 1
    The Java GC has changed over the years. For such a "focused" question the specific JVM (and options used) should be posted. However, if "generations" in the post is meant to mean a *control parents and grandparents and so on* then **it is not related to GC generations**. Modern GC's can identify the objects in these "unrooted" graphs as "unreachable" in one pass. Look up Mark and Sweep GC for some basic concepts. –  Sep 11 '12 at 20:28
  • e.g. http://blogs.msdn.com/b/abhinaba/archive/2009/01/30/back-to-basics-mark-and-sweep-garbage-collection.aspx and http://lambda.uta.edu/cse5317/notes/node47.html (of course modern GC's are much more sophisticated hybrids) –  Sep 11 '12 at 20:35

2 Answers2

2

For an empirical approach, exercise your program repeatedly and look for the pattern shown here, in which the memory consumed fails to return to baseline.

image leak

In contrast, this example returns to the baseline after each cycle.

image no leak

Community
  • 1
  • 1
trashgod
  • 196,350
  • 25
  • 213
  • 918
0

The comments to your question do a good job of addressing the deletion issue. But, if you're still curious about removing a component's children without removing the component, the answer is no, as seen in the JComponent documentation (I'm assuming you're on Java 7, if not you can easily change to the proper version of Java). If you want to quickly and easily remove just the children from a component without removing the component itself, I recommend just re-initializing the component.

Eric Hydrick
  • 3,133
  • 2
  • 25
  • 38