Search code examples
javagarbage

Object ready for Garbage collection, Java


From http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html#99740 example A3.3 says, it says that an object might still not be available for garbage collection even though it might be out of scope. IT is available only if the method is taked off stack. Now if we consider the following case:

void foo(){
Dog a = new Dog();
Dog b = new Dog();
b=a
while(true)//loop for long time
}

Will the object b referring to be available immediately for garbage collection, or only after the foo() method is returned.


Solution

  • The stack slot remains in use until the method exits. There is no JVM opcode corresponding to an inner }, so the JVM doesn't know it's gone out of the inner scope. But it does know when the method returns.