Take the 2-minute tour ×

I'm using Spring 3. When controller gets requests it passes control to method someMethod() annotated with @Async in Service bean and then returns. When I access in someMethod() HttpSession object I receive this exception

java.lang.IllegalStateException: No thread-bound request found: Are you 
referring to request attributes outside of an actual web request, or 
processing a request outside of the originally receiving thread? If you are 
actually operating within a web request and still receive this message, your 
code is probably running outside of DispatcherServlet/DispatcherPortlet: In 
this case, use RequestContextListener or 
RequestContextFilter to expose the current request.

How can I resolve this?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

The HttpSession object itself can be used in multiple threads (but is not thread-safe and therefore must be synchronized). However Spring is doing some extra magic e.g. when you have session-scoped beans. Namely it uses ThreadLocal underneath to bind current session with thread.

I don't know what is your exact scenario, but apparently Spring tries to retrieve HttpSession from this ThreadLocal while you are in another thread - which obviously fails.

The solution is simple - extract session attributes you need in @Async method and pass them directly. This is by the way much better design - avoid passing HttpSession object around because it makes testing harder and your code is much less likely to be reused in the future.

share|improve this answer
Your solution is simple and good but then where can I store user specific data if I need them not only in controller layer but also in business and data layers? Or I have to pass these data through method arguments? Is the latter the only solution? –  Oleksandr Bondarenko May 6 '12 at 20:51
@OleksandrBondarenko: Think about it - by accessing the session in your service layer you are introducing hidden coupling and non-explicit dependency. Passing all this data via arguments (possibly by wrapping it in some object) is really the best option. –  Tomasz Nurkiewicz May 6 '12 at 20:57
add comment

Your Answer


