Concurrency in real systems question 128 of 180 junior
Is a Spring singleton bean thread safe?
- Yes, Spring synchronizes bean methods
- Correct: Only if it is stateless: one instance serves every concurrent request, so any mutable field is shared
- Yes, because each request gets its own copy
- Only with
@Scope("prototype")
A singleton bean is one instance for the whole container, called by every request thread at once. Spring adds no synchronisation. Injected collaborators and configuration read at startup are fine because they are effectively immutable; a mutable field is a data race shared by every user of the application.
The failure is worse than a lost update when the field holds per-request data: a currentUser field,
or a non-thread-safe helper such as SimpleDateFormat, and now two requests see each other's data.
That is a security incident, not a bug report.
Keep state on the stack, in the request, or in a properly synchronised structure. @Scope("request")
and ThreadLocal both work and both need care: the scope proxy has a cost, and the thread local must
be cleared, because the container's thread is pooled and the next request inherits whatever was left.
Quiz yourself on Concurrency in real systems Suggest a correction