Skip to content
Ameen Abozaid
Planned lessonMID-004-L06

Immutability and confinement

  • Lesson 6 of 9
  • Mid-level
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

java
record StockSnapshot(Map<String,Integer> levels) {}   // copy on update, swap an AtomicReference

Check 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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.