Immutable objects in Java,are they really immutable?

Immutable objects in java

In this article I emphasize on using immutable objects in java and show how objects, even being immutable, can still be changed.

What are java immutable objects ?

Immutable objects are objects those state (value) cannot be changed after their creation (construction), here is an example.   


How to make an object immutable ? 

As we can see from the object above:

  • Define object’s class as final so it can’t be extended and changed; 
  • Define object’s properties as final 
  • Provide only one constructor that sets all properties 
  • No setters ! 
  • Every instance property must be immutable too !  

To give an example of the last point check the following: 


If some properties of the object in case are not immutable then the object itself is not too. However there is a work-around to solve this problem which it is to make defensive copies.  


Why immutable objects are so cool ?

There are not one or two reasons to make objects immutable and here are some, can you think of others ? 

  • Immutable objects are automatically thread-safe and have no synchronization issues: 

    Nearly all the atomicity and visibility hazards we’ve described sofar, such as seeing stale values, losing updates, or observing an object to be inan inconsistent state, have to do with the vagaries of multiple threads trying toaccess the same mutable state at the same time. Java concurrency in practice.

  • Allow hashCode to use lazy initialization, and to cache its return value:   Calculating hash code could be an expensive operation. There are some cases where hashCode() is frequently called – like when using some objects as key of map entries – calculating the hash code once and only when needed can gain performance especially when the operation is performed frequently BUT this applies only when objects are IMMUTABLE. Consider however that object can changes its state, calculating hash code once and then change the objects state will result in errors when dealing with the object.  
  • Always have “failure atomicity” (a term used by Joshua Bloch): if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state
  • Don’t need to be copied defensively when used as a field
  • To see how set can be abused by mutable objects check this link
  • Their state validation is checked once upon construction, and it never needs to be checked again
  • Make good Map keys and Set elements (these objects must not change state while in the collection) 


Everything said is wonderful but check this out :  
Even if your class is 100% immutable designed its state still can be change – with reflection – and here is how.

Output: User{name=’asd’, age=18}

Do you know how to solve this, I don’t !