Immutability in java

In Java, Object can be of two types :-
  1. Mutable
  2. Immutable
Mutable objects are the ones whose state can be changes during its lifetime. This is in contrast with Immutable objects, whose state cannot be changed once created. We have many classes in Java which provide immutable objects like String, Integer etc. In this post, I will discuss the immutability in detail, with its features and where can we use this.

In basic terms, Immutable objects are the ones, whose state cannot be changed.e.g

Integer i = new Integer(10) ;

The Integer class provides us no method which can change the state/value of i. So we say Integer is an immutable class & object i is an immutable object.

We have many benefits for it:-
  • They are good candidates to cache :- Since immutable objects do not change their state, we can share or cache them and retrieve them in future, without copying and cloning the object.
  • Solid keys :- Immutable objects makes the best keys for Hash classes. HashCode() method depends on the state variables. In case of immutable, state is consistent, the key would always return the same value. For mutable, if state changes after storing in Hash class, the hash algorithm gets confused and will return the wrong or null value.
  • Provides Thread Safety :-  In muti-threaded applications, Many issues arises due to read-write conflicts. Say, one thread going to read a object state while other simultaneously changes the state OR two threads want to write a value at the same time. To prevent this, either we use synchronize the access or can use locks, to prevent object from an inconsistent state. Its not advisable to synchronize everything as it may affect the concurrency. Here we can use Immutable objects that can be shared between threads. Since their state cannot be changed, they can used without any synchronization and simplify the writing, documentation and helps in reducing potential concurrent errors.
Everything not come as free and So as immutability. Follows are its drawbacks :-
  • Creating a lot immutable objects will have impact on the memory and may result in frequent GC. One way to avoid this is use Flyweight pattern for sharing objects whenever required.
  • Since the class is final and so as the methods, which prevent to scale the class.
How to create a perfect Immutable class:-
  • Class declared as final
  • All of its fields are final and private
  • this reference is not allowed to escape during construction.
  • If fields contains mutable objects like arrays,collections then they
    • should marked private
    • should never return or expose to callers 
    • should not provide methods to change state
One Imp Note:  If a class is final. then all its methods are implicitly final as well and the method is guaranteed not to be over-ridden as well.
 
When to use Immutable Classes :-
  • Ideal for defining abstract data types like Integer, BigDecimal, DaysOfWeek, Colors.
  • When your object needs security from outside interference. One way hacker use to control your class is by subclassing your class and access your private data and methods. Sting class is final for this reason.
  • Depends on the application like how often the objects would change (defines the synchonization level). If they change, would it meant something for the application. Application is single threaded or multi-threaded.
In case of doubts or corrections, please post a comment. In my future post, I will discuss how to use arrays in immutable class.

Comments

Popular posts from this blog

When to use getClass() and instanceOf in Java

Fix double check locking in Java 5

Generate Heap Dump in Unix