Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will using class.forname multiple times cause memory leak? (running inside tomcat)

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

like image 881
samarjit samanta Avatar asked Apr 20 '12 10:04

samarjit samanta


1 Answers

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.

like image 62
Péter Török Avatar answered Oct 08 '22 08:10

Péter Török