clearing or set null to objects in java

前端 未结 7 1667
盖世英雄少女心
盖世英雄少女心 2020-12-09 09:18

I was recently looking into freeing up memory occupied by Java objects. While doing that I got confused about how objects are copied (shallow/deep) in Java and how to avoid

7条回答
  •  孤城傲影
    2020-12-09 09:38

    I was recently looking into freeing up memory occupied by java objects.

    A piece of advice.

    It is usually a bad idea to think about this. And it is usually a worse idea to try to "help". In 99.8% of cases, the Java garbage collector is able to do a better job of collecting the garbage if you actually just let it get on with it ... and don't waste your effort by assigning null to things. Indeed, the chances are that the fields you are nulling are in objects that are about to become unreachable anyway. And in that case, the GC is not even going to look at the fields that you've nulled.

    If you take this (pragmatic) view, all your thinking about shallow versus deep copies and when it is safe to null things is moot.


    There is a tiny percentage of cases where it is advisable to assign null ... to avoid medium or long term storage leaks. And if you are in one of those rare situations where it is "recycling" objects is actually a good idea, then nulling is also advisable.

提交回复
热议问题