Are Java static variables shared across instances of the same web application?
class MyClass
{
private static SomeClass myStaticObject = new SomeClass();
}
If a web application uses MyClass and multiple instances of that application is run on a web server, is myStaticObject initialized multiple times?
Scope of Static variables. When we define a variable with a static keyword inside the class, its scope is within the class. That is, the scope of a static variable is within the class. All the methods, constructors, and blocks inside the class can access static variables by using the class name.
In Java, static members are those which belongs to the class and you can access these members without instantiating the class. The static keyword can be used with methods, fields, classes (inner/nested), blocks.
The scope of the static local variable will be the same as the automatic local variables, but its memory will be available throughout the program execution. When the function modifies the value of the static local variable during one function call, then it will remain the same even during the next function call.
The reason is, static members are shared among all objects. That is why they are also known as class members or class fields. Also, static members can be accessed without any object, see the below program where static member 'a' is accessed without any object.
Typically, yes. Most containers will provide separate classloaders for each web application. This will result in the class being loaded multiple times when used by several applications, and thus resulting in multiple instances of the static variable.
Stating the Java Language Specification for reference:
At run time, several reference types with the same binary name may be loaded simultaneously by different class loaders. These types may or may not represent the same type declaration. Even if two such types do represent the same type declaration, they are considered distinct.
By inference, multiple instances of static variables will exist, unless the classes are loaded only once by a parent class loader, and never loaded elsewhere by any other class loader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With