In the Javadoc of WeakHashMap.html, it said
"Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector."
And then
Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is, a value object may strongly refer to some other key object whose associated value object, in turn, strongly refers to the key of the first value object.
But should not both Key and Value should be used weak reference in WeakHashMap? i.e. if there is low on memory, GC will free the memory held by the value object (since the value object most likely take up more memory than key object in most cases)?
And if GC free the Value object, the Key Object can be free as well?
Basically, I am looking for a HashMap which will reduce memory usage when there is low memory (GC collects the value and key objects if necessary).
Is it possible in Java?
Thank you.
SoftReference
so far. They wait until heap becomes scarce to be freed, that the performance suffers due to increased GC activity (well, maybe in your case it will work fine). You can also use something like LRU map. Ehcache is also a possible solution. – Doordie