Question

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.

Was it helpful?

Solution

Weak references are inappropriate for caches - NetBeans does it, and can go silly.

SoftReference is what you want. It's actually quite difficult to get it right - so copy somebody else's solution. Some people advise explicitly managing caches yourself.

References only work with a single reference. There was a proposal for adding "ephemerons" to Java SE, but I haven't seen an implementation go anywhere with that.

OTHER TIPS

The idea is that you can use this Map as "lookup" data structure which only keeps the key-value-pairs alive which still can be referenced to (via a key). Still, while the basic idea is nice, I remember that it was not as useful as I hoped it would be.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top