Stateless singletons and thread safety
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
explain why singletons must not hold request state.
Planned topics
- One singleton serves many requests at the same time, on many threads.
- A mutable field (a counter, "current user") is shared by all of them: races and wrong data.
- Keep singletons stateless: only
finaldependencies, data in method variables. - State that must be shared belongs in a database or a thread-safe type, handled later.
Draft outline details
Demonstration
@Service class BadService { private int lastTotal; /* shared across requests! */ }Check your understanding
Why is private int lastTotal in a service a bug?
Show answer
Many requests share and overwrite it.
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.