I use a large (millions) entries hashmap to cache values needed by an algorithm, the key is a combination of two objects as a long. Since it grows continuously (because keys in
It sounds like you need a WeakHashMap instead:
A hashtable-based
Map
implementation with weak keys. An entry in aWeakHashMap
will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from otherMap
implementations.
I'm not sure how this works with Long
as keys, though. Also, this might be of interest:
WeakHashMap is not a cache! Understanding WeakReference and SoftReference