Java中的软引用LinkedHashMap? [英] Soft reference LinkedHashMap in Java?

查看:294
本文介绍了Java中的软引用LinkedHashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中是否存在基于softreference的LinkedHashMap?如果不是,有没有人得到我可以重用的代码片段?我保证会正确引用它。

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.

谢谢。

推荐答案

WeakHashMap不保留插入顺序。因此,它不能被视为LinkedHashMap的直接替代品。此外,仅当不再可访问时,才会发布地图条目。这可能不是你想要的。

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;
    }
}

这篇关于Java中的软引用LinkedHashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆