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
Integerkey in aWeakHashMapdoesn't prevent keys from being removed. AnIntegerkey may be garbage collected once no references exist to the sameIntegerinstance that was put into theMap. If there exist references to differentIntegerinstances equal (i.e. having the same numeric value) to a key in theWeakHashMap, that doesn't prevent the key from being automatically removed.Note that the value of your
WeakHashMapmust not hold a strong reference to the key - otherwise the key can never be automatically removed. So to avoid that, simply add values to theWeakHashMapas follows:Now, once you no longer keep a reference to the
Integerinstance referenced by thekeyvariable, theWeakHashMapwill be free to automatically remove it.If you
putthe entry in theWeakHashMapwithout keeping a reference to the key (i.e.weakMap.put(new Integer(someObject.getID()),someObject)), theWeakHashMapwill be able to auto-remove it immediately, which I don't think is what you wanted.