Aravind R. Yarram Aravind R. Yarram - 1 year ago 95
Java Question

Is using the Class instance as a Map key a best practice?

I have read somewhere that using the class instances as below is not a good idea as they might cause memory leaks. Can someone tell me if if that is a valid statement? Or are they any problems using it this way?

Map<Class<?>,String> classToInstance = new HashMap();

classToInstance.put(String.class,"Test obj");

Answer Source

Yes, you do need to be cautious! For example, if your code is running in a web container and you are in the habit of doing hot deployment of webapps, a retained reference to a single class object can cause a significant permgen memory leak.

This article explains the problem in detail. But in a nutshell, the problem is that each class contains a reference to its classloader, and each classloader contains references to every class that it has loaded. So if one class is reachable, all of them are.

From Java 8 - Permgen was removed. Do you think it is ok to use Class instance as HashMap key in any situations?

Be aware that you will still have a memory leak. Any dynamicly loaded class used in your HashMap (key or value) and (at least) other dynamically loaded classes will be kept reachable. This means the GC won't be able to unload / delete them. What was previously a permgen leak is now an ordinary heap leak.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download