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?
classObject = myObject;
would be optimized out and myObject = null;
is the point it is eligible for Garbage Collection.When an object created in Java program is no longer reachable or used it is eligible for garbage collection.
Closed 9 years ago. where it says as soon as you pass the line of code where a variable is last used, the object referenced by it is eligible for garbage collection (That is if no other variable holds a reference to that object).
as per the answer given for this question, there is no object eligible for GC at line 11; but according to me at least one object, t2, which is set to point null at line 6, should be eligible for garbage collection.
SO no, GC will never remove nulls from an array. That's not what it does. Besides which, a null value in an array is perfectly valid and removing it would break many programs.
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;
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