User Tools

Site Tools


java:immutable-objects

This is an old revision of the document!


Immutable objects

An immutable object cannot be modified after it was created. Instead, a copy of the object is returned.

Advantages

  • Thread safety: they cannot change its state, so they cannot be corrupted by thread interference or observed in an inconsistent state.
  • Atomicity of failure: if an immutable object throws an exception, it's never left in an undesirable or indeterminate state.
  • Protection against null reference errors.

Disadvantages

Immutable classes require a separate object for each distinct value. Creating these objects can be costly, especially if they are large.

How to implement an immutable object

  • methods that alters the object state should return new objects
  • make copies of caller provided data (except primitives or immutable objects)
  • ensure the class cannot be overridden (make the class final, or use static factories and keep constructors private)
java/immutable-objects.1680905302.txt.gz · Last modified: 2023/07/04 19:36 (external edit)