Immutability

Immutable objects are always thread safe. [1]

Cases

  • No fields at all.
class StatelessAdder
{
    public int add(int a, int b) { return a+b;}
}
  • Only final fields
class ImmutableAdder
{
    private final int offset;

    public ImmutableAdder(int a) { offset = a;}

    public int addOffSet(int b) { return offset+b;}
}

Applications

  • Abstract data types: Immutable objects can serve as instances of simple abstract data types representing values.
  • Value containers: Immutable objects can be used when it is necessary to establish some consistent state once and then rely on it foever more.
  • Sharing: Immutable objects are useful for sharing, since there are not any concerns about synchronization or access resitrction.
Bibliography
1. Doug lea
page_revision: 2, last_edited: 1181046710|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.