Why are immutable objecs loved by JVM's GC?

后端 未结 3 988
半阙折子戏
半阙折子戏 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:49

    If the GC can know that an object doesn't contain any references to any gen0 objects, then it can be ignored when performing a gen0 collection. Likewise if an object doesn't contain any reference to any gen0 or gen1 objects, it may be ignored when performing a gen1 collection. The more objects can be ignored during a collection, the faster that collection will be.

    If an object survives a gen0 GC, it can be sure that any gen0 object to which it had held a reference will have been promoted to gen1; likewise if an object which didn't contain any gen0 references survives a gen1 GC, any gen1 references it contained will have been promoted to gen2. Thus, once a object has been examined during a gen0 collection, it need not be examined again until the next gen1 collection, unless it is modified. Likewise an object that's examined during a gen1 collection need not be examined until the next gen2 collection unless it is modified.

    Knowing whether objects have been modified is a tricky subject, but the key point is that it's very advantageous for the GC if objects haven't been.

    0 讨论(0)
  • 2021-01-02 10:50

    Thanks for the link..found it nice :)

    From presentation : GC loves small immutable objects and short lived objects.

    Edit:

    Smaller objects have short memory footprint which means that after collection there will not be much overhead on memory compaction ( Memory compaction is slow for big object as they leave bigger memory holes after they get reclaimed by GC). And short lived objects are also good as they get collected in minor GC cycles.

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

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