gpt4 book ai didi

java - Roller 中的 session 安全违规

转载 作者:行者123 更新时间:2023-12-01 15:16:10 25 4
gpt4 key购买 nike

RollerSession有以下代码:

public static RollerSession getRollerSession(HttpServletRequest request) {
RollerSession rollerSession = null;
HttpSession session = request.getSession(false);
if (session != null) {
rollerSession = (RollerSession)session.getAttribute(ROLLER_SESSION);
if (rollerSession == null) {
// HttpSession with no RollerSession?
// Must be a session that was de-serialized from a previous run.
rollerSession = new RollerSession();
session.setAttribute(ROLLER_SESSION, rollerSession);
}
....

我是并发问题的新手。这里似乎存在原子性冲突,两个不同的线程可能同时更新 setAttribute。是对的吗?鉴于 session 是从请求获取的, session 可以由两个线程共享吗?

最佳答案

是的,你说得对,而且还有可见性问题!根据IBM's postJava Ranch get/set 操作不是线程安全的。因此,如果您不希望应用程序中存在任何竞争条件,则应该进行同步,但要小心同步的位置。

说明

执行请求线程的多个 Servlet 可能会同时主动访问同一 session 对象。容器必须确保以线程安全的方式执行表示 session 属性的内部数据结构的操作。开发人员有责任对属性对象本身进行线程安全访问。这将保护 HttpSession 对象内的属性集合免受并发访问,从而消除应用程序导致该集合损坏的机会。

这是安全的:

// guaranteed by the spec to be safe
request.getSession().setAttribute("foo", 1);

安全:

HttpSession session = request.getSession();
Integer n = (Integer) session.getAttribute("foo");
// not thread safe
// another thread might be have got stale value between get and set
session.setAttribute("foo", (n == null) ? 1 : n + 1);

-- McDowell's Answer

关于java - Roller 中的 session 安全违规,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11572210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com