Wednesday 26 August 2015

Immutable Objects Advantages

All wrapper classes in java.lang are immutable:
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger.

Thread-safe

Immutable objects are automatically thread-safe; the overhead caused due to use of synchronization is avoided.

Consistent

Once created the state of the immutable object cannot be changed so there is no possibility of them getting into an inconsistent state.

Cache

The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state cannot be changed ever after construction.

Best use as Map keys

Immutable objects are good Map keys and Set elements, since these typically do not change once created.

Easy to write
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 your program as there are no conflicts among objects.

The internal state of your program will be consistent even if you have exceptions.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...