关于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 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()
call receives a distinct instance of ServletRequest
and ServletResponse
. However, here is an example of an 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() {
}
}
由于多个线程可以访问 counter
变量,因此必须以某种方式对其进行保护:要么使用 synchronized
(volatile
还不够):
Since multiple threads can access the counter
variable, it has to be secured somehow: either by using synchronized
(volatile
is not enough):
synchronized(this) {
++counter;
}
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屋!