多个实例时Servlet同步

发布于 12-23 08:48 字数 120 浏览 2 评论 0原文

我读到 Servlet 中的代码可以与同步块同步。然而,我还了解到,虽然 servlet 通常只有一个实例,但 servlet 容器可能会保留一组实例。当然,这意味着同步块不能保证正常工作,因为您不知道请求线程将选择哪个实例?

I have read that code in servlets can be synchronized with synchronized blocks. However, I have also read that whilst there is often only one instance of a servlet the servlet container may keep a pool of instances. Surely this means that a synchronized block is therefore not guaranteed to work as you don't know which instance the request thread will choose?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清醇2024-12-30 08:48:57

规范 (3.0) 的 2.2 节说:

对于未托管在分布式环境(默认)中的 servlet,
servlet 容器每个 servlet 只能使用一个实例
声明

因此,如果容器使用实例池,则违反了规范。我不明白为什么容器会这样做,因为每个 servlet 开发人员都知道多个线程可以同时访问 servlet,因此 servlet 必须是线程安全的。

Section 2.2 of the specification (3.0) says:

For a servlet not hosted in a distributed environment (the default),
the servlet container must use only one instance per servlet
declaration

So, if a container uses a pool of instances, it's in violation of the spec. I don't see why a container would do that, since every servlet developers know that multiple threads may access the servlet concurrently, and the servlet must thus be thread-safe.

清旖2024-12-30 08:48:57

Servlet 容器确实有一个用于服务请求的线程池,这意味着可能会有多个线程执行 Servlet 代码,这意味着对任何共享可变数据的访问都需要正确同步。

Servlet containers do have a pool of threads for serving requests, which means there probably will be multiple threads executing servlets code, which means that access to any shared mutable data needs to be properly synchronized.

悟红尘2024-12-30 08:48:57

如果问题是如何使 servlet 单线程,那么其中一种方法是实现 SingleThreadModel 接口,但该接口现在已被弃用

http://docs.oracle.com/javaee/1.4/api /javax/servlet/SingleThreadModel.html

If the question is how to make servlet single threaded, then one of the approach is to implement the SingleThreadModel interface but this has now been deprecated.

http://docs.oracle.com/javaee/1.4/api/javax/servlet/SingleThreadModel.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文