问题描述
我正在使用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 SoftReference
s are quite broken.
可能我得错了......什么是正确的解决方案?
Probably I'm getting something wrongly.... what is the right solution?
只需输入值$ c $即可实现我所需要的功能c>进入每个
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
都会保留相应的值
可达,很好。此外,每个值
将保持其键
可达,但这没有问题,因为没有长时间的现有价值
。
This way, each Key
would keep its corresponding Value
reachable, which is fine. Also each Value
would keep its Key
reachable, but this is no problem as there're no long existing references to Value
.
有些到期会更好但是没有必要。
Some expiration would be better but it's not necessary.
推荐答案
不幸的是,如果没有。
这篇关于当值引用键时,如何使用弱引用进行缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!