is @Autowired HttpSession thread safe in springmvc?

给你一囗甜甜゛ 提交于 2019-12-22 12:44:00

问题


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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/14097069/is-autowired-httpsession-thread-safe-in-springmvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!