小编kir*_*tsz的帖子

使用SoftReference在Android上缓存Bitmap会导致OOM

我正在开发一个需要加载Bitmap的应用程序.并使用一个SoftReference缓存.我将每个软引用与a相关联,ReferenceQueue并使用哈希映射来访问SoftReference.如下所示:

public static class MemCache {

    final private ReferenceQueue<Bitmap> queue = new ReferenceQueue<Bitmap>();
    private Map<String, SoftReference<Bitmap>> hash = null;

    public MemCache() {
        hash = Collections.synchronizedMap(
            new LinkedHashMap<String, SoftReference<Bitmap>>()
        );
    }

    public synchronized Bitmap put(String key, Bitmap value) {
        clean();
        SoftReference<Bitmap> ref = new SoftReference<Bitmap>(value, queue);
        SoftReference<Bitmap> res = hash.put(key, ref);
        if (res == null) return null;
        return res.get();
    }

    public synchronized Bitmap get(Object key) {
        clean();
        SoftReference<Bitmap> ref = hash.get(key);
        if (ref == null) …
Run Code Online (Sandbox Code Playgroud)

java android garbage-collection out-of-memory soft-references

2
推荐指数
1
解决办法
5117
查看次数