线程安全的 Servlet
当我们创建servlet时,为什么类变量(实例和静态变量)不是线程安全的?
为什么方法doPost()
和doGet()
是线程安全的?
我认为对servlet容器的每个新请求都会创建servlet类的新实例(它扩展了HttpServlet
)。每个实例都有自己的类变量,这些变量托管在内存中,那么为什么我们必须使这些变量线程安全?
When we create servlet, why class variables(instance and static variables) are NOT thread-safe?
Why methods doPost()
and doGet()
are thread-safe?
I think that each new request to servlet container creates new instance of servlet class (which extends HttpServlet
). This each instances have they own class variables that are hosted in memory, then why we must make these variables thread safe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Servlet 仅实例化一次:加载时。然后,当客户端发出请求时,它就会被线程化。
这解释了为什么你必须在必要的地方放置监视器,等等。
由于 doGet 和 doPost 依赖于请求,因此它是线程安全的:如果你打算在 doGet 和 doPost 中执行原子操作,你应该考虑创建同步方法/块。
The servlet is instanciated only once: at loading. Then when clients make a requests, it's threaded.
This explains why you have to put monitors where it is necessary, etc.
Since doGet and doPost depend on a request, it is thread-safe : if you plan to do atomic operation in doGet and doPost, you should consider creating synchronized method/block.
Servlet 通常在多线程服务器上运行。因此,servlet 必须处理并发请求,并且应该小心同步对共享资源的访问。共享资源包括内存数据(例如实例或类变量)和外部对象(例如文件、数据库连接和网络连接)。由于多个线程可能会改变共享数据的状态,因此共享数据不是线程安全的。
如果您在这些方法中使用局部变量,doPost() 和 doGet() 是线程安全的。如果您在这些方法中改变共享变量(实例或静态变量)的状态,则 doPost() 和 doGet() 不是线程安全的。
一个 Servlet 存在一个实例。
doGet()
或doPost()
等请求会在同一实例上创建多个线程。只要您在这些方法中使用局部变量,代码就是线程安全的。您可以在这篇文章中找到很好的信息:
Servlet 是如何工作的工作?实例化、会话、共享变量和多线程
Servlets typically run on multithreaded servers. So a servlet must handle concurrent requests and should be careful to synchronize access to shared resources. Shared resources include in-memory data such as instance or class variables and external objects such as files, database connections, and network connections. Since multiple threads may mutate the state of shared data, shared data is not thread safe.
doPost() and doGet() are thread safe if you are using local variables in those methods. If you mutate the state of shared variables (instance or static variables) in these methods, doPost() and doGet() are not thread safe.
One instance exists for one Servlet. Requests like
doGet()
ordoPost()
create multiple threads on same instance. As long as you use local varaibles in these methods, code is thread safe.You can find good info in this post:
How do servlets work? Instantiation, sessions, shared variables and multithreading