Video in progress
What happens if request-specific data is stored in a field of a Spring singleton bean?
There is one bean, while requests arrive in parallel on many threads. The field becomes shared by all requests: one user's data "leaks" into another's. That is a race condition, and it only shows up under load.
📖 Answer
@Service
public class ReportService {
private Long currentUserId; // wrong: one for all requests
public Report build(Long userId) {
this.currentUserId = userId;
var data = loadData(); // in between, another thread changed currentUserId
return render(data);
}
private List<Row> loadData() { return repo.findByUser(currentUserId); }
}
In a local test everything works, because there is one request. In prod, if two users ask for a report at the same time, one may get the other's data. This is not an ordinary bug; data is leaking out.
The right way is to keep the singleton service stateless. State is passed through parameters:
public Report build(Long userId) {
var data = repo.findByUser(userId);
return render(data);
}
What can live in fields: other beans (final, through the constructor), immutable configuration, a thread-safe cache (ConcurrentHashMap, Caffeine).
If you really need a request context, use a @RequestScope bean or a parameter object (ReportContext). In code review, if you see a non-final field in a @Service class, ask about it right away.
Sign up to mark studied questions and save your progress.