If a class is loaded multiple times, do its static-members get initialized multiple times? How do I check for that?
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.
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.
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.
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.
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
}
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