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

后端 未结 4 1642
余生分开走
余生分开走 2020-12-13 03:40

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 ar

4条回答
  •  孤城傲影
    2020-12-13 04:44

    As Stephen C mentioned, the memory leak is indeed because of classloaders. But the problem is more acute than at first glance. Consider this:

    mapkey --> class --> classloader --> all other classes defined by this classloader.
    

    Furthermore,

    class --> any static members, including static Maps e.g. caches.
    

    A few such static caches can start adding up to serious amounts of memory lost whenever a webapp or some other dynamically (classloaded) loaded app is cycled.

    There are several approaches to working around this problem. If you don't care about different 'versions' of the same class from different classloaders, then simply key based on Class.getName(), which is a java.lang.String.

    Another option is to use java.util.WeakHashMap. This form of Map only maintains weak references to the keys. Weak references don't hold up GC, so they key won't cause a memory accumulation. However, the values are not referenced weakly. So if the values are for example instances of the classes used as keys, the WeakHashMap does not work.

提交回复
热议问题