Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of Java static member in web applications

Tags:

java

static

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?

like image 785
Brian Avatar asked Jun 17 '11 17:06

Brian


People also ask

What is the scope of static Java?

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.

What is the use of static member in Java?

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.

What is the scope of static variable?

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.

Why do we need static members?

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.


1 Answers

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.

like image 141
Vineet Reynolds Avatar answered Sep 28 '22 20:09

Vineet Reynolds