Is it worth to use Class as a key in a weak hash map for caching(WeakHashMap)? As know, class object is created when program starts and is destroyed when it finishes. So, is there any sence to do it or I have some misunderstanding with this?
We can conclude that to use a custom class for a key, it is necessary that hashCode() and equals() are implemented correctly. To put it simply, we have to ensure that the hashCode() method returns: the same value for the object as long as the state doesn't change (Internal Consistency)
WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as key doesn't contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.
Both null values and null keys are supported in WeakHashMap. It is not synchronized. This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator.
Simply put, the WeakHashMap is a hashtable-based implementation of the Map interface, with keys that are of a WeakReference type. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use, meaning that there is no single Reference that point to that key.
A Class is loaded when a class loader, loads it. If the ClassLoader is unloaded, so are its classes. A ClassLoader cannot be unloaded until all its classes can be cleaned up so using a Weak collection of Classes is a very good idea if you ever want to unload a class loader.
In a simple Java Se program you might have two or three class loaders which are provided for you and live for the life of the program and you never need think about them.
However if you have a container like Java EE or OSGi, these can load each application or each module in its own class loader, allowing them to be installed, upgraded or removed on the fly (without restarting the JVM)
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