HashMap with weak values

前端 未结 7 2370
悲&欢浪女
悲&欢浪女 2021-02-18 14:03

I\'m implementing a cache for Objects stored persistently. The idea is:

  • Method getObjectFromPersistence(long id); ///Takes about 3 seconds
  • M
7条回答
  •  灰色年华
    2021-02-18 14:26

    A WeakReference is added to its ReferenceQueue supplied at the construction time when its reference is collected.

    You could poll the ReferenceQueue whenever you access the cache, and hold a HashMap,Long> to know which entry to remove if a reference is found in the queue.

    Alternatively, if the cache is not frequently used, you can watch the queue in a separate thread.

提交回复
热议问题