I was going through the Java Garbage Collection process and different scenarios in which GC is applicable.
Below is the scenario I am confused about :
List<X> listX = new ArrayList<X>();
for(int a = 0;a<100;a++){
listX.add(new X(a));
}
for (X xObject : listX) {
xObject.printValue();
}
In the first loop I am adding the new objects in each loop and in the latest loop I am just printing the values, so, are those objects which I am adding in the list applicable for GC?
What does this sentence mean ?
"One more excellent example for when an instance can become eligible for garbage collection. All the properties of an instance can be stored in the register and thereafter the registers will be accessed to read the values. There is no case in future that the values will be written back to the instance. Though the values can be used in future, still this instance can be marked eligible for garbage collection"
No, they're not, since they're referenced by the array which is referenced by the ArrayList whose reference is in the stack of the current thread:
thread stack --> ArrayList --> array --> x1, x2, x3, etc.
The lifetime of the objects you add to the list is related to the lifetime of the list itself, because from what I see from the code, listX is the only object holding references to X objects.
So, X objects will be collected when listX is not referenced any longer.
Check @JBNizet to see how they are actually referenced or connected (+1). Always think like this, how my objects are connected and if they still referenced all the way back to GC Roots, and remember Java is smart, it doesn't do reference counting :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With