Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way static block is executed more than once? if so then how?

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

like image 837
learner Avatar asked May 20 '10 06:05

learner


2 Answers

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.

like image 194
Andrzej Doyle Avatar answered Sep 29 '22 04:09

Andrzej Doyle


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.

like image 23
gustafc Avatar answered Sep 29 '22 06:09

gustafc