Video in progress
Why is it dangerous to keep mutable state in a singleton bean?
A singleton bean is used by many threads at once — each HTTP request runs on its own thread. If you write request data into a field, one user's data gets mixed up with another's.
📖 Answer
A classic bug you'll see in production:
@Service
public class DiscountService {
private User currentUser; // BUG: one field shared by all requests
public BigDecimal price(User user, Product p) {
this.currentUser = user;
return calculate(p); // another thread may replace currentUser right now
}
}
Under low load the tests pass. In production, every now and then one customer gets another customer's discount — and that's very hard to track down.
What to do:
- pass data through method parameters and local variables;
- keep only immutable things in the bean: other beans, settings (
final); - if you really need a shared counter —
AtomicLong,ConcurrentHashMap; - if you need request-specific context — request scope or an explicit parameter.
Rule of thumb: a singleton service should be stateless.
Sign up to mark studied questions and save your progress.