Java servlet 范围

发布于 2024-12-29 03:02:59 字数 405 浏览 0 评论 0原文

我有一个 Web 应用程序,其中有 Servlet 和通过 getInstance 访问的静态类:

MyServlet extends HttpServet {
 protected void doGet(...) {
  MyClass.getInstance().doStuff();
 }
}

当客户端连接到 servlet 时,它们是否会获得自己的 MyClass 实例,或者此类的实例对于所有 servlet 来说是全局的?我的意思是,假设它有一个在 doGet 方法期间设置的静态变量,当其他客户端访问 Web 应用程序时,他们会获取其他客户端在该静态类中设置的变量值吗?

编辑:

具体来说, MyClass 表示访问 Web 服务的类,这是经过身份验证的。

I have a web application, which has Servlet and a static Class accessed through getInstance:

MyServlet extends HttpServet {
 protected void doGet(...) {
  MyClass.getInstance().doStuff();
 }
}

When clients connect to the servlet do they get their own intance of MyClass or the instance of this class is global to all servlets? I mean let say it have a static variable that is set during the doGet method, when other clietns access the the web app, will they get the value of the variable set by other client in this static Class?

EDIT:

Specifically, MyClass represents a class which access web services, something that is authenticated.

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

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

发布评论

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

评论(3

花想c 2025-01-05 03:02:59

Web 应用程序中的所有代码都可以访问 MyClass 的相同静态变量。

然而,它仍然必须遵守 Java 线程模型规则。

因此,在没有同步的情况下,在 doGet 中更改它并不意味着其他线程会自动看到新值。

All code in your web application will have access to the same static variable of MyClass.

However, it is still bound to play by Java thread model rules.

So, in the absence of synchronization, changing it in doGet does not mean that other threads will see the new value automatically.

十年不长 2025-01-05 03:02:59

是的,static 字段值在类加载器内共享。因此,如果 MyClass.getInstance() 返回 MyClassstatic 字段,它将被所有调用共享。

请注意,只有一个 Servlet 实例,多个线程通过其 doGet(..) 方法。

如果您需要进行一些初始化,您有两个选择:在 .getInstance() 中或在 servlet 的 init() 方法中。

Yes, a static field value is shared within the classloader. So, if MyClass.getInstance() returns a static field of MyClass, it will be shared by all invocations.

Note that there is only one servlet instance, and multiple threads pass through its doGet(..) method.

If you need to carry some initialization, you have two options: in .getInstance() or in the servlet's init() method.

迷途知返 2025-01-05 03:02:59

取决于 MyClass 的实现。如果它是单例,那么它只是 doStuff 所需的所有“实例化”的一个实例。

分享它的代码,人们会帮助你。

Depends on the implementation of MyClass. If it is a singleton, then it is only one instance for all the "instantiations" required to doStuff.

Share its code and people will help you.

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