Forcing deallocation of large cache object in Java

后端 未结 7 983
醉梦人生
醉梦人生 2021-02-04 09:36

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

7条回答
  •  鱼传尺愫
    2021-02-04 10:19

    It sounds like you need a WeakHashMap instead:

    A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap 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 other Map 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

提交回复
热议问题