Question

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.

Was it helpful?

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.

OTHER TIPS

The dog formerly knows as b should become eligible for garbage collection as soon as you re-assign the variable.

The dog known as both a and b (after that re-assignment) will remain in scope until the end of the method.

The original b (the second Dog created) is available immediately for garbage collection before the loop starts, because there is no reference held to it (both a and b reference the first Dog created).

Except the correct answers already given, your test is essentially flawed. Running empty while loop will never trigger GC as it only runs (to simplify a bit) when you run out of memory and Java needs to do some cleanup of old objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top