Softlink LinkedHashMap in Java?

Is there a LinkedHashMap link in Java? If not, does anyone have a piece of code that I can probably reuse? I promise to fix it correctly.

Thanks.

+4
source share
3 answers

WeakHashMap does not preserve the insertion order. Thus, this cannot be considered as a direct replacement for LinkedHashMap. In addition, the record on the card is displayed only when the key no longer available. Perhaps this is not what you are looking for.

If you are looking for a cache that is convenient for storing data, here is a naive implementation that 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; } } 
+6
source

The best idea I've seen for this wraps LinkedHashMap , so all you put into this is WeakReference.

UPDATE: just scanned the source of WeakHashMap and the way it handles all WeakReference while still playing well with generics is robust. The base class signature is used here:

 private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> 

I suggest viewing the source in more detail for other implementation ideas.

UPDATE 2: kdgregory raises a good point in its comment - all my suggestion is to make sure that the reference to the garbage collector will not keep links in Map . You still need to manually clear dead links.

+3
source

Check out this post . It shows how to implement SoftHashMap ...

+2
source

All Articles