Scope of Java class static member

2020-07-18 11:22发布

问题:

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?

回答1:

In the simple case, you can assume that multiple instances of Student will share the same static nextID field. However, one should think beyond the simple case (or document that you haven't). In this case, it's fine unless the instance id fields derived from the nextID 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()....



回答2:

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.