Question about WeakHashMap
Posted
by michael
on Stack Overflow
See other posts from Stack Overflow
or by michael
Published on 2010-03-18T21:19:40Z
Indexed on
2010/03/18
21:21 UTC
Read the original article
Hit count: 297
java
Hi,
In the Javadoc of "http://java.sun.com/j2se/1.4.2/docs/api/java/util/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.
© Stack Overflow or respective owner