When Is The Object Eligible For Garbage Collection?
garbage-collection, java
Solution
The object will not become a candidate for garbage collection until all references to it are discarded. Java objects are assigned by reference so when you had
classObject = myObject;
You assigned another reference to the same object on the heap. So this line
myObject = null;
Only gets rid of one reference. To make `myObject` a candidate for garbage collection, you have to have
classObject = null;
Problem
In the code below, given that `amethod` has been called. At what point/line is the Object originally referenced by `myObject`, eligible for Garbage Collection? ``` class Test { private Object classObject; public void amethod() { Object myObject = new Object(); classObject = myObject; myObject = null; } } ``` And if `classObject` or `amethod` had an access modifier of public, protected, default or static, would it affect what point the Object is eligible for Garbage Collection? If so, how would it be affected? - My first thought is that the Object is eligible for Garbage Collection when the Test object is eligible for Garbage Collection. - But then again. The optimizer may know that the classObject is never read from in which case `classObject = myObject;` would be optimized out and `myObject = null;` is the point it is eligible for Garbage Collection.