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.
Unfortunately, this is unsolvable without ephemerons.