How can one make a Java class immutable, what is the need of immutability and is there any advantage to using this?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What is an immutable object?
An immutable object is one that will not change state after it is instantiated.
How to make an object immutable?
In general, an immutable object can be made by defining a class which does not have any of its members exposed, and does not have any setters.
The following class will create an immutable object:
As can be seen in the above example, the value of the
ImmutableIntcan only be set when the object is instantiated, and by having only a getter (getValue) the object’s state cannot be changed after instantiation.However, there must be care taken that all objects that are referenced by the object must be immutable as well, or it could be possible to change the state of the object.
For example, allowing an reference to an array or
ArrayListto be obtained through an getter will allow the internal state to change by changing the array or collection:The problem with the above code is, that the
ArrayListcan be obtained throughgetListand be manipulated, leading to the state of the object itself to be altered, therefore, not immutable.One way to get around this problem is to return a copy of an array or collection when called from a getter:
What is the advantage of immutability?
The advantage of immutability comes with concurrency. It is difficult to maintain correctness in mutable objects, as multiple threads could be trying to change the state of the same object, leading to some threads seeing a different state of the same object, depending on the timing of the reads and writes to the said object.
By having an immutable object, one can ensure that all threads that are looking at the object will be seeing the same state, as the state of an immutable object will not change.