Skip to content
Ameen Abozaid
Planned lessonJNR-010-L05

Stateless singletons and thread safety

  • Lesson 5 of 6
  • Junior
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 final dependencies, data in method variables.
  • State that must be shared belongs in a database or a thread-safe type, handled later.
Draft outline details

Demonstration

java
@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.

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.