I'm having a issue with objects that are kept alive longer after its scope is gone. I know that we can't control when the GC is going to delete those objects, but my problem is that those objects are huge and consume large amount of memory. I created a toy example to show my issue. Please, consider the following code:
public class YetAnotherTest {
public static void main(String[] args) {
UniqueClass uniqueClass = new UniqueClass();
for (int i = 0; i < 5; i++) {
UniqueClass anotherUniqueClass = new UniqueClass("One more ");
uniqueClass.concat(anotherUniqueClass);
}
}
}
class UniqueClass {
String s;
public UniqueClass() {
this.s = new String();
}
public UniqueClass(String s) {
this.s = s;
}
public String getS() {
return s;
}
public void concat(UniqueClass uC) {
this.s = this.s.concat(uC.getS());
}
}
I run the above code in Debug Mode in Eclipse. When created, the object anotherUniqueClass
has id 20 as shown in the following image:
After the first iteration in the for loop, that is when anotherUniqueClass
is out of scope, I use the Eclipse debugger tool to query all alive instances of UniqueClass
. Then, we can see 2 objects alive, including the one with id 20, which is our anotherUniqueClass
out of scope. This is shown in this image:
In my real program, a machine learning algorithm, the correspondent object for anotherUniqueClass
is a huge array consuming lots of memory. That is why I am concerned about it being alive after the for loop scope. Considering that I don't have control over GC, is that any suggestion on how to get rid of that alive object? Also, by curiosity, why is it still alive longer after its scope is gone (that is, why did not GC collect it yet)?
Thanks!