How do Immutable Objects help decrease overhead due to Garbage Collection?

后端 未结 3 1954
日久生厌
日久生厌 2021-02-01 04:27

I am a newb, and I have read about Garbage Collection from the first two answers here.

Now justifying the use of Immutable Objects even if the programmer has to create n

3条回答
  •  既然无缘
    2021-02-01 05:06

    In this article Brian Goetz explains it nicely. Basically, it is related with the way garbage collector works. It has less work to do if new objects reference the old ones than vice versa.

    Excerpt from the linked article with example classes below:

    public class MutableHolder {
      private Object value;
      public Object getValue() { return value; }
      public void setValue(Object o) { value = o; }
    }
    
    public class ImmutableHolder {
      private final Object value;
      public ImmutableHolder(Object o) { value = o; }
      public Object getValue() { return value; }
    }
    

    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.

    Escape analysis

    Regarding the concern that lots of objects are created because you instantiate a new object whenever you need to change the existing one, the object allocation mechanism is much improved in latest JVMs.

    Take a look at escape analysis (also mentioned in the linked article). Many object will not be allocated on heap (but be inlined/allocated on stack), so GC will have nothing to do with them (actually GC is not aware that those objects exist at all).

    Although not related only to immutability, escape analysis mechanism can be utilised more efficiently in an immutable context (an example is the Person object which is not changed during the method invocation in the linked Oracle docs).

提交回复
热议问题