Immutable Object Pattern

The Immutable Object pattern can be used to ensure that the concurrent access to an object by several client objects does not result in any problem and makes it thread-safe. The Immutable Object pattern accomplishes this without involving the overhead of synchronizing the methods to access the object data.

To make an object immutable:

1. All instance variables (state) must be set in the constructor only. No other method should be provided to modify the state of the object. The constructor is automatically thread-safe and hence does not lead to problems.(No setter method involved)
2. It may be possible to override class methods to modify the state. In order to prevent this, declare the class as final. Declaring a class as final does not allow the class to be extended further.
3. All instance variables should be declared final so that they can be set only once, inside the constructor.
4. If any of the instance variables contain a reference to an object, the corresponding getter method should return a copy of the object it refers to, but not the actual object itself.

Usually we can make data model classes immutable. The following class is immutable:

public final class X {
  //State
  private final String a;
  private final String b;
  //Constructor
  public X(String aa, String bb) {
    a = aa;
    b = bb;
  }
  //Getters
  public String getA() {
    return a;
  }
  public String getB() {
    return b;
  }
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License