Soft reference LinkedHashMap in Java?

◇◆丶佛笑我妖孽 提交于 2019-12-04 13:24:03

问题


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.


回答1:


WeakHashMap doesn't preserve the insertion order. It thus cannot be considered as a direct replacement for LinkedHashMap. Moreover, the map entry is only released when the key is no longer reachable. Which may not be what you are looking for.

If what you are looking for is a memory-friendly cache, here is a naive implementation you could use.

package be.citobi.oneshot;

import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;

public class SoftLinkedCache<K, V>
{
    private static final long serialVersionUID = -4585400640420886743L;

    private final LinkedHashMap<K, SoftReference<V>> map;

    public SoftLinkedCache(final int cacheSize)
    {
        if (cacheSize < 1)
            throw new IllegalArgumentException("cache size must be greater than 0");

        map = new LinkedHashMap<K, SoftReference<V>>()
        {
            private static final long serialVersionUID = 5857390063785416719L;

            @Override
            protected boolean removeEldestEntry(java.util.Map.Entry<K, SoftReference<V>> eldest)
            {
                return size() > cacheSize;
            }
        };
    }

    public synchronized V put(K key, V value)
    {
        SoftReference<V> previousValueReference = map.put(key, new SoftReference<V>(value));
        return previousValueReference != null ? previousValueReference.get() : null;
    }

    public synchronized V get(K key)
    {
        SoftReference<V> valueReference = map.get(key);
        return valueReference != null ? valueReference.get() : null;
    }
}



回答2:


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<K,V> extends WeakReference<Object> implements Map.Entry<K,V>

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.




回答3:


have a look at this post. It shows how to implement a SoftHashMap...



来源:https://stackoverflow.com/questions/862648/soft-reference-linkedhashmap-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!