Java garbage collection scenario
I'm going through the Java garbage collection process and different scenarios for GC
The following is what 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 add new objects in each loop. In the latest loop, I just print values. So, what are the objects I add in the list for GC?
What does this sentence mean?
"When an instance is eligible for garbage collection, there is another good example. All the attributes of the instance can be stored in registers and then accessed to read values. These values will not appear in the future. Write back the instance. Although these values can be used in the future, this instance can still be marked as eligible for garbage collection“
Solution
No, they are not, because they are referenced by the array referenced by ArrayList, whose reference is in the stack of the current thread:
thread stack --> ArrayList --> array --> x1,x2,x3,etc.