Immutability and confinement
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
avoid locking by design.
Planned topics
- Immutable objects (final fields, no setters, records) are safe to share freely.
- Replace state by swapping a reference to a new immutable snapshot.
- Thread confinement: data used by only one thread needs no lock (local variables,
ThreadLocal). - Spring singletons are shared by all requests; keep them stateless or hold only thread-safe state.
- Copy defensively when passing mutable data across threads.
Draft outline details
Demonstration
record StockSnapshot(Map<String,Integer> levels) {} // copy on update, swap an AtomicReferenceCheck your understanding
Why is a Spring @Service with a mutable field risky?
Show answer
One instance serves all requests concurrently.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.