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

编程入门 行业动态 更新时间:2024-10-22 23:06:25
本文介绍了@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中安全吗?

本文发布于:2023-11-25 18:54:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630932.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   Autowired   HttpSession   springmvc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!