I was wondering if somebody could tell me when a Java Class
object gets garbage collected. My use case is a cache (Map<Class<?>, Class<?>[]>
) which holds the class-hierarchy of objects.
For instance:
The (short) hierarchy of String.class
would be (descending): String.class
-> Object.class
. A valid cache-entry for this type would be [KEY: String.class, VALUE: {String.class, Object.class}]
.
I guess String.class
is a bad example since the String.class should be garbage-collected....
I need this cache for a serialization project I'm working on. When writing an object my system needs the hierarchy of this object for choosing the correct "Codecs (Serializers)". Collecting the hierarchy for each object would cause some overhead which is not necessary. But then I though about memory-leaks. Probably class-objects can be garbage-collected (Which i don't know) which would not work when using strong-references in my cache.
Do you think a WeakHashMap would be enough? Or do I have to use something like:
Map<WeakReference<Class<?>>, WeakReference<Class<?>>[]> ?
What do you think about this issue?