Servlet之旅-访问attribute时的thread-safe问题

上次我们提到了由于ServletContext和HttpSession的attribute很有可能被多个threads同时访问,所以我们必须考虑thread-safe的问题。
  首先,我们来看一个解决方案,看看他是如何“试图”防止attribute被多threads访问的。
  class SafeServlet extends HttpServlet {
    public synchronized void doGet(HttpServletRequest request, HttpServletResponse response) {
        ...
        getServletContext().setAttribute("myAge", "26");
        ...
        String age = (String)getServletContext().getAttribute("myAge");
        /* age equal "26" ??? */
        ...
    }
}
Look at it! The attribute of ServletContext is absolutely safe now, I always keep other from access it when I'm accessing it! Is it cool!
Do you found the problem?
If everyone access the attirbute of ServletContext through the "SafeServlet", yes, I will say that it's safe. But...
没错,这就是问题所在,在你的web-app如果只有你一个Servlet,那么你可以用这个来解决多线程访问问题,但是现实情况可能有多个Servlet共同存在在一个web-app中,因此上述解决方案是错误的。
Below is a better solution.
  class SafeServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        ...
        ServletContext context = getServletContext();
          synchronized(context) {
            getServletContext().setAttribute("myAge", "26");
            ...
            String age = (String)getServletContext().getAttribute("myAge");
          }
        ...
    }
}
Is it safe? I have to say that "Maybe it's safe". 如果在你的web-app中所有用context的时候都象你一样对它上锁,那么我会说它是安全的。如果在你的web-app中有个流氓Servlet,它在用context时都不先申请锁,那么你所能做的就只有先把他找出来谈谈了。。。
  同样的道理也适用于HttpSession的情况,祝你愉快! 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值