Does it help GC to null local variables in Java

前端 未结 15 1921
旧巷少年郎
旧巷少年郎 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:53

    There was an old piece of Sun documentation, Java Platform Performance (link sadly now broken, and I haven't been able to find a new one), which described a situation where nulling a local variable which dropped out of scope actually had an effect on the GC.

    However, the paper referred to a very old version of java. As mentioned in this question (which also contains a précis of the problem described in the paper), this no longer affects current JVM implementations.

    0 讨论(0)
  • 2020-12-02 13:53

    To the best of my knowledge, nulling a variable immediately before it leaves the scope makes no difference to the garbage collector.

    Of course there are cases where it indeed does help. E.g. when var is not a local variable but a member or static member. Then destroying the reference might make the object unreachable and thus eligible for collection.

    Another case where it might help even with local variables if a function allocates much temporary memory to initialise some data for further processing and can throw away all references to the temporary memory before beginning the processing:

    SomeResult SomeFunction(SomeClass param) {
        TempData big = new TempData(param);
        IntermediateResult intermediate = big.GetIntermediateResult();
        big = null; // allow GC to reclaim the memory before returning from the function
        intermediate.FurtherProcessing();
        return intermediate.EvenMoreProcessing();
    }
    
    0 讨论(0)
  • 2020-12-02 13:53

    There are only two cases where I have found setting a variable to null has been useful:

    • In unit tests which create a large object in a field. The unit tester may retain the test object and the objects you created for the life of all the tests. This can cause the tester to run out of memory. In this case it is often better to use local variables instead of fields, but if a field required it can be cleared in the tearDown.
    • Circular references can be cleaned up by the GC but not with a simple incremental collection. This can mean that objects with circular references take more work to clear and can live much long than they would otherwise. Generally this doesn't matter but if you are trying to reduce your full GC time, it can help to break circular references.
    0 讨论(0)
  • 2020-12-02 13:55

    You are correct. Nulling out a variable that will immediately fall out of scope anyway is unnecessary and makes no difference whatsoever to GC. All it does is clutter the code. In Effective Java 2nd Edition, the author recommends against unnecessary nulling out of local variables. See Effective Java, 2nd Edition, Item 6: Eliminate obsolete object references, for a full writeup.

    You can also see this in the article Creating and Destroying Java Objects, at InformIT. Read the entire article to find the place where Joshua Bloch agrees with you.

    When a local variable falls out of scope, it is exactly the same as if you null the reference to it.

    EDIT: Add link to Effective Java 2nd Edition at Sun website

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-12-02 13:57

    If you don't need large objects in your local scope anymore, you can give the JVM a hint and set the reference NULL.

    public void foobar()
    {
        List<SomeObject> dataList = new ArrayList<SomeObject>();
    
        // heavy computation here where objects are added to dataList 
        // and the list grows, maybe you will sort the list and
        // you just need the first element... 
    
        SomeObject smallest = dataList.get(0);
    
        // more heavy computation will follow, where dataList is never used again
        // so give the JVM a hint to drop it on its on discretion
        dataList = null;
    
        // ok, do your stuff other heavy stuff here... maybe you even need the 
        // memory that was occupied by dataList before... 
    
        // end of game and the JVM will take care of everything, no hints needed
    }
    

    But it does not make sense before the return, because this is done by the JVM automatically. So I agree with all postings before.

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