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.
I could use weakValues(), but this could lead to very early evictions, as my values are only referenced for a short time.
Maybe I could use softValues(), but SoftReferences are quite broken.
Probably I'm getting something wrongly.... what is the right solution?
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.
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 Some expiration would be better but it's not necessary.
Unfortunately, this is unsolvable without ephemerons.
The pointer from Value -> Key doesn't matter as long as nothing else is holding on to Value.
When the Cache dumps Key, it will be collected.
If you have System->Cache->Key<-Value, when Cache drops key you get System->Cache Key<-Value. The link from Key back up to System (the memory root for this example) is broken, and Key will be recovered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With