Does it help GC to null local variables in Java

前端 未结 15 2056
旧巷少年郎
旧巷少年郎 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 13:55

    If your class hangs around for a long time, then nulling out objects it references will allow them to be collected.

    This is almost never an issue, most times nulling objects is not useful.

    When you think of object allocation and freeing, pay attention to the things that the "System" has handles to: Active threads, windows that haven't been dispose()d, and one or two more things but I can't remember right now.

    Every object in your system "Hangs" off these mount points in a giant upside-down tree. If you cut any branch free from these "Roots" the entire branch falls to the ground and is collected by the Lawn Mower of Garbage Collecting.

    Most classes need all their member variables for their entire lifecycle--and when their life is finished, their entire branch is trimmed including all their members; hence--no need to null.

    (these trims, by the way, are quite efficient, even more than C++'s free since they don't require touching each object as it's freed)

提交回复
热议问题