I have an instance of an object (Object1) whose constructor creates instances of other objects (Object2) and stores them in an ArrayList. Object2 has a static instancecount variable (among other static variables), and instances of Object2 depend on this instancecount. In a test program, I run a for loop where an instance of Object1 are created on each iteration, and then the reference to the instance of Object1 is reassigned a null value. My test program looks something like:
for (...) {
Object1 obj = new Object1(...); //which creates several Object2's
obj.myMethod();
obj = null;
}
The problem is that instances of Object2 are not getting garbage collected at the end of each loop iteration, so the static instancecount variable of Object2 just grows and grows (along with memory usage) with every iteration. Is this to be expected? Is there a way to force the cleanup of the Object2 instances so that each loop has a fresh start? Is this a bad program design?
Thanks!
Ryan
Garbage collection works pretty reliable, so it won’t leak memory or grow indefinitely.
But GC also only runs when the JVM thinks it needs to, so you cannot force it to run at the end of every iteration of your loop.
Having code that depends on when GC runs is bad code.
Also, I am not sure how you are managing the instance count. It is easy to increment it in a constructor, but when do you decrease it again? It certainly won’t happen automatically.