Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/221.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading springmvc中@Autowired HttpSession线程安全吗?_Multithreading_Spring_Thread Safety_Httpsession - Fatal编程技术网

Multithreading springmvc中@Autowired HttpSession线程安全吗?

Multithreading springmvc中@Autowired HttpSession线程安全吗?,multithreading,spring,thread-safety,httpsession,Multithreading,Spring,Thread Safety,Httpsession,我正在使用Spring MVC中的HttpSession对象与@Autowired: public abstract class UserController { @Autowired public HttpSession session; @RequestMapping(value = { "" }, method = { RequestMethod.GET }) public ModelAndView index(){ User user=(

我正在使用
Spring MVC
中的
HttpSession
对象与
@Autowired

public abstract class UserController {
    @Autowired
    public HttpSession session;

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

会话是线程安全的吗?

从Spring获得的只是HttpSession。没有特殊的螺纹安全保证

使用HttpSession的实现不一定是线程安全的。另见这个问题:

您可以通过以下方式减少竞争条件在不同步的情况下导致问题的可能性:

  • 减少会话中不会同时处理两个请求的可能性
  • 不干扰来自请求线程以外的其他线程的会话
如果需要异步处理来自会话的数据,我发现更好的策略是在请求线程中从会话中提取不可变对象,然后在服务器上的异步进程中使用这些对象。这样,您就可以尽可能避免会话的访问。也就是说,如果你需要完全安全(为什么要冒险),你需要同步

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

因此,如果您有并行请求线程,会话是线程安全的,但是如果并行线程不是请求线程,会话就变得线程不安全了?这毫无意义。会话是线程安全的。线程不安全的可能是存储在会话中的对象。@JBNizet您的解释毫无意义。事实上,我更改了措辞以避免这种情况。明确地说,HttpSession是一个接口,所以实现是线程安全还是非线程安全。规范保证某些操作是线程安全的,但并非所有实现都符合这一点。另请参见:规范中说:“容器必须确保以线程安全的方式操作表示会话属性的内部数据结构。开发人员有责任以线程安全的方式访问属性对象本身”。因此会话是线程安全的。当然,正如您链接到的IBM文章所解释的,这并不能使使用它的程序自动实现线程安全。但每个线程安全对象都是这样。你是对的@JBNizet,你同意现在的答案吗?实际上不是,但我会取消我的否决票。当涉及到正确性时,您不会“减少并发错误的机会”。通过理解您正在做的事情,您仔细地设计和编程以使代码正确。