Search code examples
multithreadingspringthread-safetyhttpsession

is @Autowired HttpSession thread safe in springmvc?


I'm using HttpSession object in Spring MVC with @Autowired:

public abstract class UserController {
    @Autowired
    public HttpSession session;

    @RequestMapping(value = { "" }, method = { RequestMethod.GET })
    public ModelAndView index(){
        User user=(User)session.getAttribute("loginUser");
    }
}

is the session thread-safe?


Solution

  • What you get wired from Spring is just the HttpSession. There are no special thread safety guarantees.

    Implementations using HttpSession are not necessarily thread safe. See also this question: Is HttpSession thread safe, are set/get Attribute thread safe operations?

    You could reduce the chances of race conditions causing problems without synchronization by:

    • reducing the chance that no two requests will be processed simultaneously for the session
    • not messing with the session from another thread than the request thread

    If you need to process data from the session asynchronously, I find it is a better strategy to pull immutable objects from the session in the request thread and then use those in asynchronous processes on the server. That way you avoid access from the session as much as possible. That said, if you need to be totally safe (why take a risk), you need to synchronize.

    synchronized(mutexFor(session)) {
      final String data = session.getAttribute("data");
      //do some work
      session.setAttribute("data", newValue);
    }