当值引用键时,如何使用弱引用进行缓存? [英] How to cache with weak references when values refer back to keys?

查看:284
本文介绍了当值引用键时,如何使用弱引用进行缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Guava的缓存< Key,Value> 。每当 Key 不再强烈可达时,缓存条目应该被垃圾收集(某天......)。使用 CacheBuilder.weakKeys()如果没有来自 Value 的引用返回

I'm using Guava's Cache<Key, Value>. Whenever Key is no more strongly reachable, the cache entry should be garbage collected (someday...). Using CacheBuilder.weakKeys() would do exactly that, if there weren't a reference from Value back to Key.

我可以将此引用设为弱,但这可以随时使我的完全无效。我可以处理它,但我不愿意。

I could make this reference weak, but this could anytime make my Value quite invalid. I could handle it, but I'd prefer not to.

我可以使用 weakValues(),但是这个可能会导致很早的驱逐,因为我的价值仅在短时间内被引用。

I could use weakValues(), but this could lead to very early evictions, as my values are only referenced for a short time.

也许我可以使用 softValues(),但 SoftReference s 相当破碎

Maybe I could use softValues(), but SoftReferences are quite broken.

可能我得错了......什么是正确的解决方案?

Probably I'm getting something wrongly.... what is the right solution?

只需输入进入每个 Key ,但这是不可能的,因为 Key 不在我的控制范围内。如果是,那么我不需要缓存,没有弱引用,什么也不需要。

What I need could be achieved simply by putting a reference to Value into each Key, but this is not possible as Key is not under my control. If it was, then I'd need no cache, no weak references, nothing.

这样,每个 Key 都会保留相应的可达,很好 1 。此外,每个将保持其可达,但这没有问题,因为没有长时间的现有价值

This way, each Key would keep its corresponding Value reachable, which is fine1. Also each Value would keep its Key reachable, but this is no problem as there're no long existing references to Value.

1 有些到期会更好但是没有必要。

1 Some expiration would be better but it's not necessary.

推荐答案

不幸的是,如果没有 ephemerons

这篇关于当值引用键时,如何使用弱引用进行缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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