Volley框架缓存过大导致oom

博客讨论了Volley框架在缓存过大时引发的OOM异常。文章指出,由于Volley不适用于大量数据缓存,因此当缓存过大时会出现内存溢出问题。作者提出了清理Volley缓存的解决方案,包括在获取请求队列时清除DiskBasedCache。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

exception:

java.lang.OutOfMemoryError: Failed to allocate a 1852142714 byte allocation with 8388608 free bytes and 229MB until OOM

            at com.android.volley.toolbox.DiskBasedCache.streamToBytes(DiskBasedCache.java:321)

            at com.android.volley.toolbox.DiskBasedCache.readString(DiskBasedCache.java:531)

            at com.android.volley.toolbox.DiskBasedCache.readStringStringMap(DiskBasedCache.java:554)

            at com.android.volley.toolbox.DiskBasedCache$CacheHeader.readHeader(DiskBasedCache.java:397)

            at com.android.volley.toolbox.DiskBasedCache.initialize(DiskBasedCache.java:155)

            at com.android.volley.CacheDispatcher.run(CacheDispatcher.java:84)


volley本来就不建议用来缓存太多的数据。遇到这种情况,目前的最好的解决方案貌似只有暴力清理缓存。


下面就贴下清理缓存的方法:

在获取请求队列的时候,拿到DiskBasedCache的引用,然后通过ClearCacheRequest来清理掉volley的缓存

private RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        File cacheDir = new File(this.getCacheDir(), "volley");
        DiskBasedCache cache = new DiskBasedCache(cacheDir);
        mRequestQueue.start();

        // clear all volley caches.
        mRequestQueue.add(new ClearCacheRequest(cache, null));
        return mRequestQueue;
    }


ps:volley默认的缓存放在/data/data/包名/cache/volley 下
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值