Does variable = null set it for garbage collection

后端 未结 8 1443
走了就别回头了
走了就别回头了 2020-11-27 19:04

Help me settle a dispute with a coworker: Does setting a variable or collection to null in Java aid in garbage collection and reducing memory usage? If I have a long running

相关标签:
8条回答
  • 2020-11-27 19:31

    It is useless on local variables, but it can be useful/needed to clear up instance variables that are not required anymore (e.g. post-initialization).

    (Yeah yeah, I know how to apply the Builder pattern...)

    0 讨论(0)
  • 2020-11-27 19:31

    That could only make some sense in some scenario like this:

    public void myHeavyMethod() {
      List hugeList = loadHugeListOfStuff();  // lots of memory used
      ResultX res = processHugeList(hugeList); // compute some result or summary 
      // hugeList = null;  // we are done with hugeList
        ...
      // do a lot of other things that takes a LOT of time (seconds?)
      // and which do not require hugeList
       ...
    }
    

    Here it could make some benefit to uncomment the hugeList = null line, I guess.

    But it would certainly make more sense to rewrite the method (perhaps refactoring into two, or specifying an inner scope).

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