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



