1) If I use the following Class.forName() is called multiple times, will it cause memory leaks?
Class.forName("MyClass")
2) Or, is tomcat's WebAppClassLoader going to check whether "MyClass"
is already loaded and use the cached instance instead.
3) If the answer to question (2) is 'no' then, will the previously loaded class gets garbage collected, if I have switched on PermGen sweeping on and set relevant jvm parameters.
If I want to avoid reloading of class, what is the best way to use class instance cache. Can I store class instance as HashMap
1) No, one class definition is only loaded once by any given classloader. After that, it is kept in memory (in PermGen space) and reused on subsequent references to the class, till the classloader exists. This is independent of how the class is referenced: via Class.forName
, ClassLoader.loadClass
or whatever.
The same class definition can be loaded into different classloaders multiple times though (resulting in multiple class token objects in memory). These count as totally different classes, which can't be cast to each other, even if they were loaded from exactly the same class file.
2) Yes
3) N/A
4) the referenced article mentions that the class is reloaded in a different classloader, so my explanation under 1) applies.
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