Soft reference LinkedHashMap in Java?

前端 未结 3 1939
误落风尘
误落风尘 2021-02-10 16:49

Is there softreference-based LinkedHashMap in Java? If no, has anyone got a snippet of code that I can probably reuse? I promise to reference it correctly.

Thanks.

3条回答
  •  失恋的感觉
    2021-02-10 17:35

    The best idea I've seen for this is wrapping LinkedHashMap so that everything you put into it is a WeakReference.

    UPDATE: Just browsed the source of WeakHashMap and the way it handles making everything a WeakReference while still playing nice with generics is solid. Here's the core class signature it uses:

    private static class Entry extends WeakReference implements Map.Entry
    
    
    

    I suggest browsing the source more in depth for other implementation ideas.

    UPDATE 2: kdgregory raises a good point in his comment - all my suggestion does is make sure the references in the Map won't keep the referent from being garbage-collected. You still need to clean out the dead references manually.

    提交回复
    热议问题