Why are immutable objecs loved by JVM's GC?

后端 未结 3 1016
半阙折子戏
半阙折子戏 2021-01-02 10:23

I know the reason that JVM GC loves short-live object because it can be collected in minor GC. But why does JVM GC love immutable objects?

EDIT: Charlie Hunt says t

3条回答
  •  天涯浪人
    2021-01-02 10:53

    I found the answer from Brian Goetz's article.

    In most cases, when a holder object is updated to reference a different object, the new referent is a young object. If we update a MutableHolder by calling setValue(), we have created a situation where an older object references a younger one. On the other hand, by creating a new ImmutableHolder object instead, a younger object is referencing an older one. The latter situation, where most objects point to older objects, is much more gentle on a generational garbage collector. If a MutableHolder that lives in the old generation is mutated, all the objects on the card that contain the MutableHolder must be scanned for old-to-young references at the next minor collection. The use of mutable references for long-lived container objects increases the work done to track old-to-young references at collection time.

提交回复
热议问题