Does it help GC to null local variables in Java

前端 未结 15 1922
旧巷少年郎
旧巷少年郎 2020-12-02 13:06

I was \'forced\' to add myLocalVar = null; statement into finally clause just before leaving method. Reason is to help GC. I was told I will get SMS\'s during n

相关标签:
15条回答
  • 2020-12-02 14:00

    That is a myth that goes way back to when java first came out and C++ guys didn't trust the gc.

    The gc knows what it is doing. nulling out var wont hurt anything, but it wont really help anything either. Jeff had a pretty funny post on this just the other day.

    0 讨论(0)
  • 2020-12-02 14:00

    I don't know the technical details, but as far as I can remember, the variable is nothing more than reference from the current stack frame, and until this reference is removed, the object cannot be garbage collected. Now, but explicitly setting it to null, you've made sure that the reference is gone. If you don't you're basically letting the VM decide when this reference is cleared, which might or might not be upon exiting the scope (unlike C++, if the object is located on the stack and MUST be destroyed). It might be when the stack frame is overwritten with the next. I'm not sure if there's actually a VM which does this.

    Short answer though, it's unnecessary, the mark and sweep will get it eventually. It's at most a question of time.

    0 讨论(0)
  • 2020-12-02 14:03

    In some circumstances, it can be useful to null variables (usually instance or class variables). But nulling a local variable immediately before the end of the method does absolutely nothing.

    When you set a variable to null, you are merely removing that reference to the actual object. But when a local variable goes out of scope, the reference is removed anyway; therefore, setting it to null as the last line of the method is simply redundant.

    0 讨论(0)
提交回复
热议问题