Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a class is loaded multiple times, do its static-members get initialized multiple times?

If a class is loaded multiple times, do its static-members get initialized multiple times? How do I check for that?

like image 570
One Two Three Avatar asked Aug 07 '14 16:08

One Two Three


People also ask

Can the static variable be initialized multiple times?

A static variable declaration is only executed once, the first time the function is executed. A static variable is initialized only once (since this is part of the declaration process) and will be initialized to 0 unless the programmer designates otherwise.

How many times static member variable is initialized?

A static variable in a block is initialized only one time, prior to program execution, whereas an auto variable that has an initializer is initialized every time it comes into existence.

Can we initialize static variable multiple times in Java?

When a variable is declared as static, space for it gets allocated for the lifetime of the program. Even if the function is called multiple times, space for the static variable is allocated only once and the value of variable in the previous call gets carried through the next function call.

Can the same class be loaded by multiple ClassLoaders in Java?

A class is always identified using its fully qualified name (package. classname). So when a class is loaded into JVM, you have an entry as (package, classname, classloader). Therefore the same class can be loaded twice by two different ClassLoader instances.


1 Answers

If there are different classloaders involved, then they will be completely separate classes, with separate static fields etc - and each will be initialized separately.

(The simplest way to diagnose this is just to log when you get initialized, of course...)

static {
    // Log initialization
}
like image 200
Jon Skeet Avatar answered Nov 23 '22 23:11

Jon Skeet