Reputation: 845
Will it be safe to use a bean, with request or session scope, asynchronously in a separate thread that is created from the main thread that handles a request?
I was wondering what will happen if a request completes or a session expires and the child thread is still active. Will spring destroy the bean or is it aware that the bean is still in use.
I'm just familiarizing myself with bean scopes and life cycles in spring. Please pardon my noobness.
Upvotes: 1
Views: 1366
Reputation: 8064
Short answer: it is not safe, copy the information you need to do your asynchronous processing.
Long answer: Spring implements request scoped beans using proxies. This proxy is what gets injected into your classes. Whenever you call a method on this proxy, Spring will look up the actual bean that is valid for the current request (using a ThreadLocal
mechanism) and then delegate the call to the correct instance.
As soon as the request thread finishes though, the associated request scoped beans are cleared (so as not to interfere with the next time the same thread is used for a different request). They're not "destroyed", but since you only have an indirect reference to them (through the proxy that gets injected) they're effectively unaccessable and will get garbage collected.
If after the request has finished you try to call one of the methods on the proxy and there is no valid request anymore, Spring will throw you an exception.
Upvotes: 2