Saturday 4 February 2012

Immutable Classes

If you can instantiate an object of a class but can never change any of the values of the data fields (instance variables) of the instantiated object, the class is called an immutable class. An immutable class has all private data fields and none of the methods change the data field values. You pass in the values to initialize the data fields to, in the constructor. So the internal state of an object is fixed at the time of its creation. After that time, any methods which appear to modify the data fields actually return newly instantiated objects with data fields initialized to the modified values.

Java's String, Integer, Long, Float, Double and Boolean classes are immutable. Once instantiated, you cannot change their value.

Immutable classes are thread-safe. You don't have to synchronize any operations on them. Variables declared within a method body or within a block of code are always thread-safe. It is only when you have instance variables or class variables (i.e. static variables) that thread-safety concerns arise. That's when a thread may read a set of variables while another thread is in the middle of modifying that set of variables. (Individual variable assignments are also thread-safe.) If you cannot ever modify the instance variables of an object (immutable class), thread-safety concerns do not arise.

How to make a class immutable :
  •     ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
  •     make fields private and final
  •     force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
  •     do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
  •     if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller

No comments:

Post a Comment