Advantages and disadvantages immutable objects in Java Java 24.11.2013
Advantages of immutable objects:
- An immutable object remains in exactly one state, the state in which it was created. Therefore, immutable object is thread-safe so there is no synchronization issue. They cannot be corrupted by multiple threads accessing them concurrently. This is far and away the easiest approach to achieving thread safety.
- Immutable classes are easier to design, implement, and use than mutable classes.
- Immutable objects are good
Map
keys and Set
elements, since these typically do not change once created.
- Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged).
- Immutability makes it easier to parallelize program as there are no conflicts among objects.
- The internal state of program will be consistent even if you have exceptions.
- References to immutable objects can be cached as they are not going to change. (i.e. in Hashing it provide fast operations).
Disadvantages of immutable objects:
Creating an immutable class seems at first to provide an elegant solution. However, whenever you do need a modified object of that new type you must suffer the overhead of a new object creation, as well as potentially causing more frequent garbage collections. The only real disadvantage of immutable classes is that they require a separate object for each distinct value.