Servlet线程安全

public class servletDemo1 extends HttpServlet {
    int i=0;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {        
        i++;
        System.out.println(i);
    }
}
public class servletDemo1 extends HttpServlet {    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {        
        int i=0;
        i++;
        System.out.println(i);
    }
}

如果有100个请求同时访问这个Servlet,很明显,上面两段代码,第一个会有线程安全问题,而第二个没有

解决的办法

就是放在同步代码块里面

public class servletDemo1 extends HttpServlet {  
int i=0;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { synchronized (this) { i++; System.out.println(i); } } }

这样一个线程来了,其他线程就要等了。

很显然,这种单线程访问的形式,解决方案是行不通的。

Servlet中的解决方式,

使用SingleThreadModel接口

(这种接口里面什么也没有,成为标记接口,如果一个类实现了这种接口,就相当于有一个标记)

只要打上这个标,就是线程安全的了

Serializable这个接口也是标记接口

(Java中的类默认是不允许被序列化的,实现这个接口就可以了)

Cloneable接口也是一样

public class servletDemo1 extends HttpServlet implements SingleThreadModel{    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {        
        synchronized (this) {        
            int i=0;
            i++;
            System.out.println(i);
        }
    }
}


这种方法具体的细节就是如果一个请求调用了Servlet对象,当另一个请求也到来时,发现使用了线程安全,就会再创建一个Servlet对象。

这种方式已经过时了。

原文地址:https://www.cnblogs.com/tech-bird/p/3824671.html