【发布时间】:2017-04-25 23:58:17
【问题描述】:
考虑到会话变量本质上不是线程安全的,什么是在 servlet 中初始化会话变量的干净利落的方法?
考虑以下代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// NOT thread safe
if( request.getSession().getAttribute("mySessionVariable") == null )
request.getSession().setAttribute("mySessionVariable", new AtomicInteger(0));
((AtomicInteger) request.getSession().getAttribute("mySessionVariable")).incrementAndGet();
}
在上面的代码中,有可能两个线程会同时看到变量为空,因此都将其初始化为 0。为了避免这种情况,当然可以使用同步块:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
synchronized(this){
if( request.getSession().getAttribute("mySessionVariable") == null )
request.getSession().setAttribute("mySessionVariable", new AtomicInteger(0));
((AtomicInteger) request.getSession().getAttribute("mySessionVariable")).incrementAndGet();
}
}
但我想知道,有没有更清洁和“更漂亮”的方法来实现同样的目标?
【问题讨论】:
标签: java multithreading session servlets