是否提供良好的缓存

是否提供良好的缓存

本文介绍了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 是否提供良好的缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 08:46