java 关于servlet的线程安全

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11485486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:17:53  来源:igfitidea点击:

Regarding thread safety of servlet

javamultithreadingservletsthread-safety

提问by user1508454

Possible Duplicate:
How do servlets work? Instantiation, session variables and multithreading

可能的重复:
servlet 是如何工作的?实例化、会话变量和多线程

Is servlet is thread safe ..? For ex If I open 5 different browsers and sending request to one servlet in the container , is it still thread safe , I means the service()method specially

servlet 是线程安全的吗?例如,如果我打开5个不同的浏览器并向容器中的一个servlet发送请求,它是否仍然是线程安全的,我service()特意指的是该方法

回答by Tomasz Nurkiewicz

Your question boils down to: is calling a method from multiple threads on the same object thread safe. And the answer is: it depends. If your object (let it be servlet) is stateless or has only finalfields, this is completely thread safe. Local variables and parameters are local to the thread (reside on stack, not on heap).

您的问题归结为:在同一对象 thread safe 上从多个线程调用方法。答案是:这取决于。如果您的对象(让它成为 servlet)是无状态的或只有final字段,则这完全是线程安全的。局部变量和参数对于线程来说是局部的(驻留在栈上,而不是堆上)。

Also each service()call receives a distinct instance of ServletRequestand ServletResponse. However, here is an example of an unsafe servlet:

此外,每个service()调用都会收到一个不同的ServletRequestand实例ServletResponse。但是,这里有一个不安全 servlet 的示例:

public class UnsafeServlet implements Servlet {

    private int counter;

    public void init(ServletConfig config) throws ServletException {
    }

    public void service(ServletRequest request, ServletResponse response)
        ++counter;
    }

    public void destroy() {
    }

}

Since multiple threads can access the countervariable, it has to be secured somehow: either by using synchronized(volatileis not enough):

由于多个线程可以访问该counter变量,因此必须以某种方式对其进行保护:使用synchronized(volatile还不够):

synchronized(this) {
    ++counter;
}

or AtomicInteger:

AtomicInteger

private AtomicInteger counter = new AtomicInteger();

//...
counter.incrementAndGet();

In this particular case AtomicIntegeris much better since it is lock-free using CAS CPU operations while synchronizedis a mutex.

在这种特殊情况下AtomicInteger要好得多,因为它使用 CAS CPU 操作synchronized是无锁的,而它是互斥锁。