Why are immutable objecs loved by JVM's GC?

后端 未结 3 989
半阙折子戏
半阙折子戏 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.

提交回复
热议问题