Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache with weak references when values refer back to keys?

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?

Update

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.

like image 888
maaartinus Avatar asked Oct 27 '25 07:10

maaartinus


2 Answers

Unfortunately, this is unsolvable without ephemerons.

like image 179
Kevin Bourrillion Avatar answered Oct 29 '25 21:10

Kevin Bourrillion


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.

like image 45
Will Hartung Avatar answered Oct 29 '25 22:10

Will Hartung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!