Does variable = null set it for garbage collection

后端 未结 8 1487
走了就别回头了
走了就别回头了 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

    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).

提交回复
热议问题