I encountered this question in an interview:
Is an object created inside of a method eligible for garbage collection after the method is finished?
Is yes the correct answer?
I encountered this question in an interview:
Is an object created inside of a method eligible for garbage collection after the method is finished?
Is yes the correct answer?
Well it depends - it's eligible for garbage collection as soon as there are no more "live" references to it. If you've done something within the method which means there are still live references after the method has finished, then no - the object won't be eligible for garbage collection. For example:
public class Test
{
private Object field;
public void foo()
{
field = new Object();
}
public Object getField()
{
return field:
}
}
// Elsewhere
Test t = new Test();
t.foo();
Object x = t.getField();
The object created in foo()
is certainly not eligible for garbage collection when foo()
has completed - after all, we want to fetch it in the next line of code!
Assuming that a reference to that object was not handed to something else that's still in scope when the method exits, then yes.
An object can be garbage collected when there are no references to it, or every object that references it is also being garbage collected.
public int getThing() {
Object o = new Object();
return 5;
}
Here, o can be garbage collected after the method, because nothing points to it.
Object o = null;
public int getThing() {
o = new Object();
return 5;
}
Here it can't, because other things can still reference o since it's a class member.
public Object getThing() {
Object o = new Object();
return o;
}
Here it can't be, because it's being returned. If the caller holds on to it, it stays alive.
If someone has a pointer to it, it stays alive (roughly).
The only thing i would like to add to the answers above is that an object is not eligible for garbage collection as long as there is a strong reference to it from within a non-eligible object.
There are Weak references (and a few other kinds, for that matter) that make objects they point to collectable, even though the reference itself is still there. You can see WeakHashMap and related for more info.