@Autowired HttpSession线程在springmvc中安全吗? [英] is @Autowired HttpSession thread safe in springmvc?

查看:580
本文介绍了@Autowired HttpSession线程在springmvc中安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Spring MVC@Autowired中使用HttpSession对象:

public abstract class UserController {
    @Autowired
    public HttpSession session;

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

会话是线程安全的吗?

推荐答案

从Spring获得的连接只是HttpSession.没有特殊的线程安全保证.

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

使用HttpSession的实现不一定是线程安全的.另请参阅以下问题: HttpSession线程是否安全,设置/获取属性线程安全操作?

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:

  • 减少会话中不会同时处理两个请求的机会
  • 不会弄乱请求线程之外的其他线程的会话

如果您需要异步处理会话中的数据,我发现这是一种更好的策略,即从请求线程中的会话中提取不可变对象,然后在服务器上的异步过程中使用它们.这样,您将尽可能避免从会话进行访问.就是说,如果您需要完全安全(为什么要冒险),则需要进行同步.

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

这篇关于@Autowired HttpSession线程在springmvc中安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆