Thursday, March 7, 2013

immutable class



  • What is immutable class in Java

Immutable classes are those class, whose object can not be modified once created, it means any modification on immutable object will result in another immutable object. best example to understand immutable and mutable objects are, String and StringBuffer.
Since String is immutable class, any change on existing string object will result in another string e.g. replacing a character into String, creating substring from String, all result in a new objects.
While in case of mutable object like StringBuffer, any modification is done on object itself and no new objects are created.
Some times this immutability of String can also cause security hole, and that the reason why password should be stored on char array instead of String.

advantages
1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.
2) Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.
3) Immutable object boost performance of Java application by reducing synchronization in code.

disadvantages
Since immutable object can not be reused and they are just a use and throw.
String being a prime example, which can create lot of garbage and can potentially slow down application due to heavy garbage collection

http://javarevisited.blogspot.com/2013/03/how-to-create-immutable-class-object-java-example-tutorial.html#ixzz2Mry69OKV



  • What is immutable object? Can you write immutable object?
You need to make class final and all its member final so that once objects gets created no one can modify its state.
You can achieve same functionality by making member as non final but private and not modifying them except in constructor

No comments:

Post a Comment