0

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?

2
  • 2
    The answer depends on more things than are stated in your question. The interviewer was probably waiting for you to ask the relevant questions -- they were wondering how much you know about garbage collection, which can be determined from what you ask them in response. Nov 2, 2009 at 21:23
  • Yes, provided it is not referenced by a "path to root", i.e. it is not referenced by another non-finalizable object.
    – rsp
    Nov 2, 2009 at 21:38

4 Answers 4

9

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).

3

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!

1

Assuming that a reference to that object was not handed to something else that's still in scope when the method exits, then yes.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.