I want to use a WeakHashMap
for objects that will exist in memory for a short time.
Each object has an id (unique integer field which is a primary key from DB), so my 1st thought was to use that field as the key for the object.
However, Integer is immutable, so AFAIK, the hash will produce another immutable Integer and thus the object will not be GCed as long as any other non related object points to it.
Is there a way to use an Integer key in a WeakHashMap
?
Using an Integer
key in a WeakHashMap
doesn't prevent keys from being removed.
An Integer
key may be garbage collected once no references exist to the same Integer
instance that was put into the Map
. If there exist references to different Integer
instances equal (i.e. having the same numeric value) to a key in the WeakHashMap
, that doesn't prevent the key from being automatically removed.
Note that the value of your WeakHashMap
must not hold a strong reference to the key - otherwise the key can never be automatically removed. So to avoid that, simply add values to the WeakHashMap
as follows:
Integer key = new Integer(someObject.getID());
weakMap.put(key,someObject);
Now, once you no longer keep a reference to the Integer
instance referenced by the key
variable, the WeakHashMap
will be free to automatically remove it.
If you put
the entry in the WeakHashMap
without keeping a reference to the key (i.e. weakMap.put(new Integer(someObject.getID()),someObject)
), the WeakHashMap
will be able to auto-remove it immediately, which I don't think is what you wanted.