What is an immutable object?
An immutable object is one that does not change state after it is created.
How to make an object immutable?
In the general case, an immutable object can be created by defining a class that does not have any of its members and does not have any setters.
The following class will create an immutable object:
class ImmutableInt { private final int value; public ImmutableInt(int i) { value = i; } public int getValue() { return value; } }
As can be seen from the above example, the value of ImmutableInt can only be set when creating an instance of the object, and if there is only a getter ( getValue ), the state of the object cannot be changed after the instance is created.
However, care must be taken to ensure that all objects referenced by the object must also be immutable, or the state of the object could be changed.
For example, allowing you to get a reference to an array or ArrayList , which will be obtained through a getter, will allow you to change the internal state by changing the array or collection:
class NotQuiteImmutableList<T> { private final List<T> list; public NotQuiteImmutableList(List<T> list) {
The problem with the above code is that ArrayList can be obtained using getList and manipulated, which will lead to a change in the state of the object itself, so it is not immutable.
// notQuiteImmutableList contains "a", "b", "c" List<String> notQuiteImmutableList= new NotQuiteImmutableList(Arrays.asList("a", "b", "c")); // now the list contains "a", "b", "c", "d" -- this list is mutable. notQuiteImmutableList.getList().add("d");
One way around this problem is to return a copy of the array or collection when called from the receiver:
public List<T> getList() {
What is the advantage of immutability?
The advantage of immutability comes with concurrency. It is difficult to maintain correctness in mutable objects, since several threads may try to change the state of the same object, resulting in some threads seeing a different state of the same object, depending on the time of reading and writing to the said object.
Having an immutable object, we can guarantee that all threads that look at the object will see the same state, since the state of the immutable object will not change.