without any synchronization and without fear of any state curruption because immutable object can not change there state once created.
Immutable objects are essential for concurrent program String in java is immutable and wrapper classes are also immutable , immutable objects are good keys in java hashmap and they can be shared between multiple thread without using synchronization in java. here are some of steps to make a class immutable in java:
To create a class immutable, you need to follow following steps:
- you need to declare the class as final so it can’t be extended.2.you have to Make all fields private so that direct access is not allowed.3.Please Don’t provide setter methods for variables
- makes sure that all mutable fields final so that it’s value can be assigned only once.
- don’t forget to Initialize all the fields via a constructor performing deep copy.6.don’t forget to perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
I hope you like this immutable object tutorial stay tuned for more java tips.