Close

Mutable vs Immutable Objects

[Last Updated: Dec 7, 2016]

Java 

An immutable object is an object whose state cannot be modified after it is created. It's read only Object.

State of a mutable object can be changed after it is created.

An mutable object might cause some sync problems. For example, Java Collection/Map containing mutable objects as its elements. Assume a SortedSet is populated with mutable objects. If after insertion, a particular element changes it's state outside: that change might invalidate the sorted order in the collection. Same problem arises for HashSets: changing element state outside can invalidate the object hash-code. Also mutable objects might have side effects in concurrent situations.

Mutable object should be used in a local context only . If not possible then there could be solutions like observable collections or thread locking etc.

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

See Also