My Understanding Static block is executed during class loading, If a class is already loaded then there is no way to load the class other than class reloading
Doubt/Question 1) Is there any time JVM reloads the class?
My Understanding In Class Loading JVM loads bytecode of the Java file, so it can not keep all thousands classes bytecode in memory, so it might be discarding the rarely used code and reloading it again when it is necessary and during reload JVM is not initializing static variables and blocks again(may be using some tracking mechanism)
Doubt/Question
2) If my above understanding is incorrect then please correct me
To my knowledge the JVM will never reload a class per se; once a class is loaded it stays loaded forever. Class definitions are held in the "PermGen" memory pool for this reason.
However, it is possible for your 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, whereas typically any classloader can see your bytecode if it's on the classpath, so this is a possible (if undesirable) situation.
Classes can be unloaded if the ClassLoader
loading them becomes unreachable: https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.7
A class or interface may be unloaded if and only if its defining class loader may be reclaimed by the garbage collector as discussed in §12.6.
Then, if the class needs using again, it will obviously be loaded again. And in fact, several classloaders can load the same class separately, in parallell.
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