【发布时间】:2009-04-15 03:06:05
【问题描述】:
参考Brian Goetz 为IBM developerWorks 撰写的文章Are all stateful Web applications broken?,我想参考这段代码
HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart)session.getAttribute("shoppingCart");
if (cart == null) {
cart = new ShoppingCart(...);
session.setAttribute("shoppingCart", cart);
}
doSomethingWith(cart);
据我所知,这段代码不是线程安全的,因为它使用 check-then-act 模式。但我有一个疑问:
第一行中HttpSession 的创建或检索不是完全原子的吗?原子,我的意思是如果两个线程调用request.getSession(),一个会阻塞。尽管两者都将返回相同的 HttpSession 实例。因此,如果客户端(移动/Web 浏览器)进行两次或调用同一个 Servlet(执行上面的 sn-p),您将永远不会遇到不同线程看到 cart 的不同值的情况。
假设我确信它是不线程安全的,如何使这个线程安全? AtomicReference 会起作用吗?例如:
HttpSession session = request.getSession(true);
AtomicReference<ShoppingCart> cartRef =
(<AtomicReference<ShoppingCart>)session.getAttribute("shoppingCart");
ShoppingCart cart = cartRef.get();
if (cart == null) {
cart = new ShoppingCart(...);
session.setAttribute("shoppingCart",
new AtomicReference<ShoppingCart>(cart));
}
doSomethingWith(cart);
谢谢!
【问题讨论】:
标签: java multithreading servlets concurrency