Jatin
Jatin

Reputation: 31724

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.

Upvotes: 0

Views: 1557

Answers (4)

user207421
user207421

Reputation: 310859

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.

Upvotes: 5

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

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.

Upvotes: 0

Bohemian
Bohemian

Reputation: 424983

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

Upvotes: 1

Thilo
Thilo

Reputation: 262474

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.

Upvotes: 2

Related Questions