If I have a java class like below
public class XXX {
static {
...
...
}
}
And if the JVM ( because of GC triggered by Permgen ) unloads the class and loads it later again, will the static block get called twice?
If I have a java class like below
public class XXX {
static {
...
...
}
}
And if the JVM ( because of GC triggered by Permgen ) unloads the class and loads it later again, will the static block get called twice?
Quoting from this other post: https://stackoverflow.com/a/148707/641955
The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo.
If that's what you're doing, then yes, the static block will get executed twice during the lifetime of your program, once each for the lifetime of each classloader.
Yes. You could also use different class loaders to load the class multiple times and the static block would be called for each load.
When JVM loads a class it stays loaded and class definitions are held in the PermGen
memory pool for this reason.
However, it is possible for the class' bytecode to be loaded by multiple classloaders, and each time this happens the static block will be executed again as this is a new class. Each class is only visible within the scope of its own classloader.
And if the JVM ( because of GC triggered by Permgen ) unloads the class and loads it later again, will teh static block get called twice ?
Yes it should.
The static initializer is executed only once per ClassLoader.
For a exhaustinc explanation have a look into section JLS 12.4.2
"A class or interface type T will be initialized immediately before the first occurrence of any one of the following:"
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10) lexically nested
within T (§8.1.3) is executed.