Java类静态成员的作用域
我正在使用 Java/JSP 开发 Web 应用程序。 一个类(比如 Student)有一个静态成员 static private int _nextID;
我想知道,这个_nextID在所有用户会话中是否相同?或者每个会话都有自己的_nextID?
I am developing a web application using Java/JSP.
One class, say Student, has a static member
static private int _nextID;
I want to know, if this _nextID is the same among all user sessions? Or each session has its own _nextID?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在简单的情况中,您可以假设
Student
的多个实例将共享相同的静态nextID
字段。然而,人们应该超越简单的案例(或你没有的文档)来思考。在这种情况下,除非从nextID
计数器派生的实例id
字段传播到更大的应用程序中,其中 ID 应该是唯一的,否则就没有问题。在这种情况下,您需要一个更强大的 ID 生成器(也许您需要一个 UUID;也许您想要数据库中的主键;也许是其他东西)。仔细问问自己,唯一 ID 所需的范围是什么。然后寻找解决该问题的解决方案并将其记录在课堂上。
一般来说,同名类中的静态字段,但由不同的类加载器(在相同或不同的 JVM 中)加载,可能是 不同的实例,这是人们在尝试实现单例模式时最常注意到的事情。因此,静态变量的范围取决于(在复杂的情况下)相关的类加载器。有关 由类加载器定义的 Java 命名空间的更多(最新)详细信息位于此处 和此处。
与SO相关:
Thread.getContextClassLoader 之间的差异()
...。In the simple case, you can assume that multiple instances of
Student
will share the same staticnextID
field. However, one should think beyond the simple case (or document that you haven't). In this case, it's fine unless the instanceid
fields derived from thenextID
counter propagate out into a larger application where the IDs are meant to be unique. In that case, you want a more robust ID generator (maybe you want a UUID; maybe you want a primary key in a database; maybe something else).Ask yourself carefully what the required scope of the unique IDs is. Then seek a solution that solves that problem and document it in the class.
In general, static fields within the same-named class, but loaded by different classloaders (in the same or in different JVMs) may be different instances, something people most often notice when trying to implement the Singleton pattern. So the scope of your static variable depends (in complicated cases) on the relevant classloaders. Some more (recent) detail about Java namespaces defined by classloader is here and here.
Related on SO: Difference between
Thread.getContextClassLoader()
....这取决于您的应用程序容器和配置。
对于在 JVM 实例中运行的所有会话,静态成员都是相同的,但您的配置可能会创建多个实例。
如果您想保持其一致性和可移植性,则不应依赖它在所有会话中都相同。如果需要,这还可以让您扩展到多台机器,而无需更改此代码。
It depends on your application container and the configuration.
A static member will be the same for all sessions running within a JVM instance, but your configuration may be creating multiple instances.
If you want to keep this consistent and portable, you should not rely on it being the same across all sessions. This can also allow you to scale to multiple machines if needed without changing this code.