Java static member scope in web applications

Are Java static variables bound between instances of the same web application?

class MyClass { private static SomeClass myStaticObject = new SomeClass(); } 

If the web application uses MyClass , and several instances of this application are launched on the web server, is myStaticObject initialized several times?

+6
source share
2 answers

Generally yes. Most containers provide separate class loaders for each web application. This will cause the class to be loaded several times when used by multiple applications, and therefore lead to multiple instances of the static variable.

Note Java language specification for reference:

At run time, multiple reference types with the same binary name can be loaded simultaneously by different classes. These types may or may not represent the same type of declaration. Even if two of these types present the same type of declaration, they are considered distinct.

In conclusion, there will be several instances of static variables, unless the classes are loaded only once by the parent class loader and never loaded anywhere by the other class loader.

+8
source

I see no reason to have a private static variable in MyClass . If it is private , you cannot access it as a class variable outside the class in which you defined it. If you just want other classes to access this variable using the getter method, you must remove the static .

-one
source

All Articles