开发者

Must set a strong reference to null after use in Java when using WeakReference?

开发者 https://www.devze.com 2023-04-03 15:12 出处:网络
I was reading this due to some memory issues I was having in my code relating to weak references, when I came across this little note:

I was reading this due to some memory issues I was having in my code relating to weak references, when I came across this little note:

You have to explicitly set that strong reference to null after use:

This one isn't so obvious: you might think that a s开发者_Go百科trong reference ceases to exist once it goes out of scope. However, the JVM isn't required to do so, and for efficiency's sake, won't. The strong reference remains in the stack frame, and can get in the way of garbage collection.

Is this still true? If I do something like:

void foo(){
    Object obj = weakRef.get();
    doStuffWith(obj);
}

Is it required that I set obj = null when I'm done with the method, or else I'll leak obj?


It is true that JVM isn't required to do so. As a matter of fact, JVM isn't required to do GC at all.

But a JVM that doesn't nullify a local reference is as unreasonable as a JVM that doesn't do GC.

(Well, there are people who give gigantic memory to JVM, and turn off GC completely; they simply restart the app every N days.)

0

精彩评论

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

关注公众号