开发者

Object ready for Garbage collection, Java

开发者 https://www.devze.com 2023-03-28 07:02 出处:网络
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 migh

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)//l开发者_Python百科oop for long time
}

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消