Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak hash map with Class key

Tags:

java

class

map

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?

like image 633
Alexander Bezrodniy Avatar asked Sep 25 '12 07:09

Alexander Bezrodniy


People also ask

Can we use class as key in HashMap?

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)

What is a weak HashMap?

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.

Does WeakHashMap allow null keys?

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.

When should we use WeakHashMap?

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.


1 Answers

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)

like image 127
Peter Lawrey Avatar answered Sep 25 '22 05:09

Peter Lawrey