Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Soft reference LinkedHashMap in Java?

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.

like image 457
His Avatar asked Dec 22 '22 11:12

His


1 Answers

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;
    }
}
like image 158
frroland Avatar answered Jan 01 '23 03:01

frroland