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
Regarding thread safety of servlet
提问by user1508454
Possible Duplicate:
How do servlets work? Instantiation, session variables and multithreading
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 final
fields, 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 ServletRequest
and ServletResponse
. However, here is an example of an unsafe servlet:
此外,每个service()
调用都会收到一个不同的ServletRequest
and实例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 counter
variable, it has to be secured somehow: either by using synchronized
(volatile
is not enough):
由于多个线程可以访问该counter
变量,因此必须以某种方式对其进行保护:使用synchronized
(volatile
还不够):
synchronized(this) {
++counter;
}
or AtomicInteger
:
private AtomicInteger counter = new AtomicInteger();
//...
counter.incrementAndGet();
In this particular case AtomicInteger
is much better since it is lock-free using CAS CPU operations while synchronized
is a mutex.
在这种特殊情况下AtomicInteger
要好得多,因为它使用 CAS CPU 操作synchronized
是无锁的,而它是互斥锁。