Does it help GC to null local variables in Java

前端 未结 15 2002
旧巷少年郎
旧巷少年郎 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: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 dataList = new ArrayList();
    
        // 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.

提交回复
热议问题