关于servlet的线程安全性 [英] Regarding thread safety of servlet
问题描述
可能重复:
servlet如何工作?实例化,会话变量和多线程
servlet是线程安全的吗?例如,如果我打开5个不同的浏览器并向容器中的一个servlet发送请求,它是否仍然是线程安全的,我的意思是 service()
方法
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)是无状态的或者只有 final
字段,那么这完全是线程安全的。局部变量和参数是线程的本地变量(驻留在堆栈上,而不是堆上)。
Your question boils down to: is calling a method from multiple threads on the same object is 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).
此外每个 service()
调用接收 ServletRequest
和 ServletResponse
的不同实例。但是这里是一个不安全的servlet的例子:
Also each service()
calls receives distinct instance of ServletRequest
and ServletResponse
. However here is an example of unsafe 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() {
}
}
由于多个线程可以访问计数器
变量,因此必须以某种方式保护它:通过使用 synchronized
( volatile
还不够):
Since multiple threads can access counter
variable, it has to be secured somehow: either by using synchronized
(volatile
is not enough):
synchronized(this) {
++counter;
}
或 AtomicInteger
:
private AtomicInteger counter = new AtomicInteger();
//...
counter.incrementAndGet();
在这种特殊情况下 AtomicInteger
要好得多因为它使用CAS CPU操作是无锁的,而 synchronized
是一个互斥锁。
In this particular case AtomicInteger
is much better since it is lock-free using CAS CPU operations while synchronized
is a mutex.
这篇关于关于servlet的线程安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!