liveBook · Manning

Immutability

As explained in Spring Start Here, Second Edition

Immutability is the property that an object's state cannot be changed after initialization.

An immutable object cannot have its state changed after initialization. This matters when multiple threads share a singleton bean: changing shared state can cause race conditions and unexpected results. section 5.1.1

In Spring applications, practical ways to preserve immutability include:

  • Use constructor injection and final fields for dependencies, as with CommentService’s CommentRepository. section 5.1.1
  • Avoid field injection when a field must be final; this supports controlling its value at initialization. section 3.2.1
  • Prefer Java records for HTTP request and response data carriers when constraints allow. section 10.3.1
Figure 5.5 When multiple threads access a singleton bean, they access the same instance. If these threads try to change the instance simultaneously, they run into race conditions. The race condition causes unexpected results or execution exceptions if the bean is not designed for concurrency.

The diagram illustrates why simultaneous changes to a shared singleton instance can cause race conditions. section 5.1.1

How Spring Start Here, Second Edition covers it

How deep it goes
Explains final fields and race-condition risks, but does not detail synchronization implementation.
Examples
Uses a final CommentRepository dependency, contrasts field-injected Parrot, and recommends records for HTTP data carriers.
What it assumes
Assumes a Spring bean and dependency-injection context; explains why field injection prevents final fields.
What you can do after
Apply it by using constructor injection and final dependencies for singleton beans, or records for HTTP data carriers.
How it connects
Connects constructor injection, singleton scope, race conditions, and data transfer objects.

Also explained in

Compare how 4 books explain immutability →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.