问题
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.
回答1:
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.
Reference
s 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.
回答2:
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.
来源:https://stackoverflow.com/questions/2473410/reduce-memory-usage-with-weakhashmap