WeakReference 是一个很好的缓存吗? [英] Does WeakReference make a good cache?

查看:24
本文介绍了WeakReference 是一个很好的缓存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个缓存,它使用对缓存对象的 WeakReferences 使它们在内存压力的情况下自动从缓存中删除.我的问题是缓存的对象在存储在缓存中后很快就会被收集.缓存在 64 位应用程序中运行,尽管仍有超过 4gig 的内存可用,但所有缓存对象都会被收集(此时它们通常存储在 G2 堆中).正如进程浏览器所示,没有手动引发的垃圾收集.

i have a cache that uses WeakReferences to the cached objects to make them automatically removed from the cache in case of memory pressure. My problem is that the cached objects are collected very soon after they have been stored in the cache. The cache runs in a 64-Bit application and in spite of the case that more than 4gig of memory are still available, all the cached objects are collected (they usually are stored in the G2-heap at that moment). There are no garbage collection induced manually as the process explorer shows.

我可以应用什么方法让物体活得更久一点?

What methods can i apply to make the objects live a litte longer?

推荐答案

使用 Wea​​kReferences 作为引用缓存对象的主要方法并不是一个好主意,因为正如 Josh 所说,您在未来对 WeakReference 进行任何行为更改的支配和GC.

Using WeakReferences as the primary means of referencing cached objects is not really a great idea, because as Josh said, your at the mercy of any future behavioral changes to WeakReference and the GC.

但是,如果您的缓存需要任何类型的复活功能,对等待清除的项目使用 Wea​​kReferences 是有用的.当一个项目满足驱逐标准时,而不是立即驱逐它,您将其引用更改为弱引用.如果在 GC 之前有任何请求,您可以恢复它的强引用,并且该对象可以再次存活.我发现这对于一些难以预测命中率模式且复活"频率足够高的缓存很有用.

However, if your cache needs any kind of resurrection capability, use of WeakReferences for items that are pending purge is useful. When an item meets eviction criteria, rather than immediately evicting it, you change its reference to a weak reference. If anything requests it before it is GC'ed, you restore its strong reference, and the object can live again. I have found this useful for some caches that have hard to predict hit rate patterns with frequent enough "resurrections" to be beneficial.

如果您有可预测的命中率模式,那么我会放弃 WeakReference 选项并执行明确的驱逐.

If you have predictable hit rate patterns, then I would forgoe the WeakReference option and perform explicit evictions.

这篇关于WeakReference 是一个很好的缓存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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